powershellregistrykey

Registry Key Exist True of False Output


I have what I would consider a simple power shell script that I am trying to run. The script will basically check for the existence of the RegKey and return a value with an output of 0 or 1.

The issue I have is that my test results are not consistent. Ex. Reg key does not exists and the script is executed the correct value is returned, 0. I manually add the key to the registry and run the script again expected a Write-Output of 1 but 0 is what is being returned. Now if I change the parameter in the if statement from $null to something like $false then the correct output is returned until I go back and repeat my test process. I hoping that someone may have the time to take a look at what I have written and point me in the right direction.

New-PSDrive -PSProvider registry -Root HKEY_CLASSES_ROOT -Name HKCR
Test-Path -Path 'HKCR:\Installer\UpgradeCodes\59DD538593C91FA40B60EB02250187C0*'
if($path -eq $null) {Write-Output 0}
else
{Write-output 1} 
 remove-psdrive -name HKCR

Solution

  • Therefore:

    if (Test-Path -Path registry::HKEY_CLASSES_ROOT\Installer\UpgradeCodes\59DD538593C91FA40B60EB02250187C0*) {
      1  # same as: Write-Output 1
    }
    else {
      0  # same as: Write-Output 0
    }
    

    If, by contrast, you wanted to get the specific key(s) that the wildcard expression matches, use Get-Item:

    $path = Get-Item -Path registry::HKEY_CLASSES_ROOT\Installer\UpgradeCodes\59DD538593C91FA40B60EB02250187C0*
    if ($null -eq $path) {  # Always place $null on the LHS
      'not found'
    }
    else {
      'found at least one'
    }
    

    [1] Note that HKEY_CLASSES_ROOT is actually a composite view of two distinct registry subtrees: the machine-level HKEY_LOCAL_MACHINE\Software\Classes and the user-level HKEY_CURRENT_USER\Software\Classes. That is, you see the union of keys from these subtrees in HKEY_CLASSES_ROOT; if a registry value exists in both locations, the HKEY_CURRENT_USER value takes precedence.