Search code examples
powershellregistrydword

PowerShell Get-ItemProperty not finding DWORD in registry


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:

  • When running the script, if there's a key with the same name, the script would output "Property already exists".
  • When running the script, if there's not a key with the same name, the script would create the key and output "Created".

What happens:

  • If the key exists, but is type DWORD, the script just outputs "Created". If I keep running the script several times, it still says "Created".
  • If I delete the key, and create it as type SZ, the script functions as expected.

So basically, for some reason, I'm unable to code the script to also discover DWORD type keys.


Solution

  • 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."
    }