# Exit script if required variables are not defined
If ( !$TdrLevel ) { Write-Error "TdrLevel must be defined, this script will now exit." ; Exit }
If ( !$TdrDelay ) { Write-Error "TdrDelay must be defined, this script will now exit." ; Exit }

# Set the root registry path
$RegPath = 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers'

# Get/set the TDR level
$ExistingTdrLevel = [Microsoft.Win32.Registry]::GetValue($RegPath,'TdrLevel',3)
If ( $TdrLevel -ne $ExistingTdrLevel ) {
    # Set the TDR level
    #   Note: 1 = Disable, 3 = Recover (default)
    Write-Output "Existing TDR level:    ${ExistingTdrLevel}"
    Write-Output "Changing TDR level to: ${TdrLevel}"
    [Microsoft.Win32.Registry]::SetValue($RegPath,'TdrLevel',$TdrLevel,[Microsoft.Win32.RegistryValueKind]::DWord)
} Else {
    Write-Output "TDR level is already set to ${TdrLevel}"
}

# Get/set the TDR delay
$ExistingTdrValue = [Microsoft.Win32.Registry]::GetValue($RegPath,'TdrDelay',2)
If ( $TdrDelay -ne $ExistingTdrValue ) {
    # Setting TDR timeout to $TdrDelay seconds
    #   Note: 2 = Default
    Write-Output "Existing TDR delay:    ${ExistingTdrValue}"
    Write-Output "Changing TDR delay to: ${TdrDelay}"
    [Microsoft.Win32.Registry]::SetValue($RegPath,'TdrDelay',$TdrDelay,[Microsoft.Win32.RegistryValueKind]::DWord)
} Else {
    Write-Output "TDR delay is already set to ${TdrDelay}"
}
