4

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
Omer
  • 43
  • 1
  • 3
  • 1
    Where does your `$path` variable come from? Instead of evaluating its value, you should evaluate the result of `Test-Path`. – stackprotector Apr 11 '20 at 10:21
  • 2
    In any case, [`$null` should be on the lefthand side of the equality operator](https://stackoverflow.com/q/58217913/1701026) – iRon Apr 11 '20 at 10:43

1 Answers1

8
  • Test-Path, like all Test-* cmdlets in PowerShell, returns a Boolean value, i.e. either $true or $false, so you shouldn't compare it to $null; instead, simply use it as-is in a conditional.

  • There is no need to create a PowerShell drive just so you can access the HKEY_CLASSES_ROOT hive[1]; you can simply use the registry:: PS provider prefix to access a native registry path.

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775