Why Test-Path doesn't work in HKEY_LOCAL_MACHINE, but only HKLM:
I found behavior in Powershell that looks very inconsistent and confusing, mostly different notation when accessing registry keys and what syntax is expected (as an argument) or supplied (as a return value) by different commands, especially this means:
HKEY_LOCAL_MACHINE ... versus HKLM \
Let me show you an example:
$baseDir = "HKLM:\System\CurrentControlSet\Enum\SCSI"
$Results = Get-ChildItem $baseDir -Recurse -ErrorAction SilentlyContinue
foreach ($item in $Results)
{
$Subkey = $item.Name
$keyExists = Test-Path "$Subkey" -PathType Container -ErrorAction SilentlyContinue
if ($keyExists -eq $False)
{
New-Item $Subkey
}
}
So what happens is this:
$Subkey = $item.Name
returns HKEY_LOCAL_MACHINE \ System \ CurrentControlSet \ Enum \ SCSI \ SomePath
and
$keyExists = Test-Path "$Subkey" -PathType Container -ErrorAction SilentlyContinue
doesn't work with this syntax, i.e. returns "$ false" even though the path exists.
As a workaround, I introduced a sequence of lines of code between these two lines, which fixes the problem:
$Subkey = $Subkey -replace "HKEY_LOCAL_MACHINE", "HKLM:"
This works - it changes the line: HKLM: \ System \ CurrentControlSet \ Enum \ SCSI \ SomePath so Test-Path can work with this syntax, but it's not very smart.
What am I missing at all? Why doesn't powershell return the result names from Get-ChildItem in a way that is suitable for further processing in powershell? Why not always use the same syntax style?
For me this is a design flaw in Powershell, or is there another way to fix this?
(Note: this is just a stripped down example showing the main problem, I know there is no point in looking for children and checking for its existence ...)
source to share
HKLM:
is a valid PSDrive, HKEY_LOCAL_MACHINE
not.
PS C:\> Get-PSProvider Registry | select -Expand Drives
Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
HKLM Registry HKEY_LOCAL_MACHINE
HKCU Registry HKEY_CURRENT_USER
Use Test-Path
items for property PSPath
instead of your property Name
.
source to share