I am wanting to to test if a registry key exists by using Test-Path:
if((Test-Path -Path 'HKLM:\SOFTWARE\IDTSettings') -eq $true) {
echo "Registry Key Exists, Ignoring this machine."
exit
}
else {
...
I manually created this key in the registry and it looks like this:
However, running this script will never exit and instead it will go into the else statement.
To test this I tried Test-Path -Path 'HKLM:\SOFTWARE\IDTSettings'
in the Windows Terminal and it responded with the appropriate True.
I am confused why these are different and would love if anyone would be able to help with this.
Many thanks
EDIT:
Weirdly if I run the powershell script from Windows Terminal it will detect the registry key fine but If I try to run it from PowerShell ISE it doesn't work. This does fix my problem as the script works properly when I call it so I will close this question. Thank you all for trying to help :)
As you have confirmed, the problem was that you ran your script from the 32-bit version of the ISE, which sees different, 32-bit-application-specific registry information in the HKEY_LOCAL_MACHINE\SOFTWARE
subtree (which, expressed as a PowerShell path, is equivalent to HKLM:\SOFTWARE
).
If use of the 32-bit ISE was accidental (check if the window title ends in (x86)
), simply run the 64-bit version instead (e.g., run powershell_ise
from a 64-bit PowerShell or cmd.exe
session, which launches C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell_ise.exe
)
Otherwise, see below.
If you really must test the existence of a key in the 64-bit HKEY_LOCAL_MACHINE\SOFTWARE
subtree from a 32-bit process, more work is needed; one option is to use reg.exe
:
if ($(reg.exe query 'HKEY_LOCAL_MACHINE\SOFTWARE\IDTSettings' /reg:64 *>$null; -not $LASTEXITCODE)) {
"Registry key exists, ignoring this machine."
exit
}
else {
# ...
}
Note that the inverse solution - accessing a 32-bit key from a 64-bit process would be simpler: the 32-bit data is accessible via the HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node
subtree
(if (Test-Path 'HKLM:\SOFTWARE\Wow6432Node\IDTSettings') { ... }
)