I'm trying to create a script that first checks if there's a key in the registry, and if there isn't; creates it.
$path = "HKCU:\Software\Microsoft\Office\16.0\Common\Identity\"
$regkey = "Testkey"
$keyvalue = "0"
if ((Get-ItemProperty $path -Name $regkey -ea 0).$regkey) {
"Property already exists"
} else {
Set-ItemProperty -Path $path -Name $regkey -Value $keyvalue
Write-Output "Created key."
}
What I expect:
What happens:
So basically, for some reason, I'm unable to code the script to also discover DWORD type keys.
The issue is with the way you check for the presence of the registry value. You're getting the value, expand its data, and then let PowerShell evaluate the data in a boolean context. A numeric value of 0 in that context evaluates to $false
, but a string value "0" evaluates to $true
because it's a non-empty string. Likewise a non-zero numeric value would evaluate to $true
and a string "" would evaluate to $false
.
To fix the issue you need to check if the registry lookup actually returns a non-empty result:
if ((Get-ItemProperty $path -Name $regkey -EA 0).$regkey -ne $null) {
"Property already exists"
} else {
Set-ItemProperty -Path $path -Name $regkey -Value $keyvalue
Write-Output "Created key."
}