Reputation: 443
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?
Upvotes: 2
Views: 829
Reputation: 440536
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).
Upvotes: 4