I'm using PowerShell 5.1.
I have a script that retrieves the HKLM:\SYSTEM\CurrentControlSet\Services<service>\ImagePath value from the registry. The string that gets returns looks like this:
"C:\Program Files\Dir1\Dir2"
Note that the double quotes are part of the string.
I need to get the parent directory for the path represented by this string. I tried Split-Path
, but this leaves the leading double quote in the returned value, which causes Test-Path
to return false
on a directory that does indeed exist. For example,
$key = "HKLM:\SYSTEM\CurrentControlSet\Services\<service>"
$val = "ImagePath"
$dir = Get-RegistryValue $key $val
: "C:\Program Files\Dir1\Dir2"
$parentDir = Split-Path $dir
: "C:\Program Files\Dir1 <--leading double quote
Test-Path $parentDir
: False
To get around this, I tried using the Trim()
call to remove any leading or trailing double-quotes, but that only seems to remove the leading double quote, i.e., the trailing double quote remains in place. This looks like a bug to me based on my experience with String.Trim()
in C#.
$key = "HKLM:\SYSTEM\CurrentControlSet\Services\<service>"
$val = "ImagePath"
$dir = (Get-RegistryValue $key $val).Trim("`"")
: C:\Program Files\Dir1\Dir2" <-- trailing double quote
The only thing that seems to work is to replace the double quotes with an empty string, like so:
$key = "HKLM:\SYSTEM\CurrentControlSet\Services\<service>"
$val = "ImagePath"
$dir = (Get-RegistryValue $key $val).Replace("`"", "")
: C:\Program Files\Dir1\Dir2 <-- no double quotes
However, this just feels wrong to me. It works in this case given that paths cannot have double quotes, i.e., the double quote character is an illegal path variable. But what if the returned registry value legitimately had a double quote in the string? This brute approach would remove that double quote.
I'm still new to PowerShell, so it's very possible that I'm overlooking something that will do what I want to do without requiring me to use the Replace()
call. Any help is greatly appreciated.
Trim('"')
not working? Perhaps there are also trailing invisible characters.. you coult tryTrim('" ')
– TheoTrim('"')
leaves the same trailing quote. I triedTrim('" ')
and that works, so there must be some trailing space there. Didn't think of trying that, so kudos for that. Is this the best way to do it? – Matt DavisTrim().Trim('"')
to get rid of all surrounding whitespace first and then unquote – Theo