$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 ) {
        LogMsg "Hardware assisted GPU scheduling is already enabled"
        $HardwareGPUSchedulingEnabled = $true
    }
}
If ( $HardwareGPUSchedulingEnabled -eq $false ) {
    LogMsg "Hardware assisted GPU scheduling is disabled"
    $HardwareGPUSchedulingEnabled = $false
}

# Find a GPU in the system so we can enable GPU scheduling
If ( $HardwareGPUSchedulingEnabled -eq $false ) {
    LogMsg "  - 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 ) {
        LogMsg "  - GPU found!"
        LogMsg "Enabling hardware assisted GPU scheduling"
        Try {
            New-ItemProperty -Path $key -Name $name -PropertyType DWord -Value 2 -Force -ErrorAction Stop
            LogMsg "A restart is required before this change will take effect"
        }
        Catch { LogErr $_.Exception.Message }
    } Else {
        LogMsg "  - No GPU was found"
        LogMsg "Hardware assisted GPU scheduling will not be enabled"
    }
}
