$key = "HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers"
$name = "HwSchMode"

# Check to see if GPU scheduling is enabled
$HardwareGPUSchedulingEnabled = $false
If ( Test-RegistryProperty -Path $key -Name $name ) {
    $setting = (Get-ItemPropertyValue -Path $key -Name $name -ErrorAction SilentlyContinue)
    If ( $setting -eq 2 ) {
        Write-Output "Hardware assisted GPU scheduling is already enabled"
        $HardwareGPUSchedulingEnabled = $true
    }
}
If ( $HardwareGPUSchedulingEnabled -eq $false ) {
    Write-Output "Hardware assisted GPU scheduling is disabled"
    $HardwareGPUSchedulingEnabled = $false
}

# Find a GPU in the system so we can enable GPU scheduling
If ( $HardwareGPUSchedulingEnabled -eq $false ) {
    Write-Output "  - Attempting to find a discrete Nvidia or AMD GPU"
    $GPUs = (Get-WmiObject Win32_VideoController).Name
    $FoundDiscreteGPU = $false
    ForEach ( $gpu in $GPUs ) {
        If ( $gpu -ilike "*NVIDIA*" ) {
            $FoundDiscreteGPU = $true
        }
    }

    # If we found a discrete GPU, enable hardware assisted GPU scheduling
    If ( $FoundDiscreteGPU -eq $true ) {
        Write-Output "  - GPU found!"
        Write-Output "Enabling hardware assisted GPU scheduling"
        Try {
            New-ItemProperty -Path $key -Name $name -PropertyType DWord -Value 2 -Force -ErrorAction Stop
            Write-Output "A restart is required before this change will take effect"
        }
        Catch { Write-Error $_.Exception.Message }
    } Else {
        Write-Output "  - No GPU was found"
        Write-Output "Hardware assisted GPU scheduling will not be enabled"
    }
}
