Home > Blockchain >  Set a value for a DWORD32 value in the registry only if it already exists | PowerShell
Set a value for a DWORD32 value in the registry only if it already exists | PowerShell

Time:12-24

I want to set a value for DWORD32 value in the registry only if it already exists.

This is my code:

Set-ItemProperty -Path $mypath -Name $myname -Value 0

The problem with this code is in the Set-ItemProperty class; It creates the DWORD32 value even if it doesn't exist, and I want to change its value only if it exists.

Any solutions?

CodePudding user response:

Check if Get-ItemPropertyValue returns any success output while ignoring any errors (in PSv4-, use Get-ItemProperty):

if ($null -ne (Get-ItemPropertyValue -ErrorAction Ignore -LiteralPath $mypath -Name $myname)) {
  Set-ItemProperty -LiteralPath $mypath -Name $myname -Value 0
}

Note:

  • The above just tests whether the registry value exists - it doesn't check its data type. For the latter, you could use (the value returned by Microsoft.Win32.RegistryKey.GetValueKind() is of type Microsoft.Win32.RegistryValueKind):

    (Get-Item -LiteralPath $path).GetValueKind($myName) -eq 'Dword'
    
  • Note that use of Test-Path is not an option in this case, because it can only test for provider items (which map to registry keys), not also their properties (which map to registry values).

  • Related