0

I'm trying to use Test-Path in the registry, sample code:

$RegistryLocation = "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"

This works fine:

Test-Path -Path $RegistryLocation

True. Now without the final asterisk character:

$NewRegistryLocation = $RegistryLocation.Split("*")
Test-Path -Path $NewRegistryLocation

Cannot bind argument to parameter 'Path' because it is an empty string.

But this works (value of $NewRegistryLocation variable):

Test-Path -Path "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"

What is happening here?

2
  • 1
    Wouldn't split("*") create an array with the second value being null (part after * in the original string)? Null would result in error. Commented May 1, 2018 at 10:58
  • 1
    $NewRegistryLocation is not a string but a string array. You can view it's type by $NewRegistryLocation.GetType(). Use$NewRegistryLocation[0] Commented May 1, 2018 at 10:58

2 Answers 2

5

The Split() method breaks the string in two every time it finds the character(s) you give it, producing an array. It isn't just removing the character from the end of the string.

There are a number of ways to get around this in your case:

  1. If possible, don't add the asterisk to the string in the first place
  2. Use only the first item in the array: $NewRegistryLocation = $RegistryLocation.Split("*")[0]
  3. Use Split-Path (which does what I think you intended): $NewRegistryLocation = Split-Path -Path $RegistryLocation -Parent
  4. use the -replace operator to remove the asterisk: $NewRegistryLocation = $RegistryLocation -replace "\*",""

Method 3 is probably what I'd recommend as it's a bit more robust and 'PowerShelly'.

Sign up to request clarification or add additional context in comments.

Comments

2

Try to replace this line

$NewRegistryLocation = $RegistryLocation.Split("*")

with this

$NewRegistryLocation = $RegistryLocation.Split("*")[0]

so your NewRegistryLocation will still contain a string and not an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.