Test-Path -Path显示为空字符串

Lig*_*War 0 powershell

我正在尝试Test-Path在注册表中使用示例代码:

$RegistryLocation = "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
Run Code Online (Sandbox Code Playgroud)

这很好用:

Test-Path -Path $RegistryLocation
Run Code Online (Sandbox Code Playgroud)

真正.现在没有最后的星号字符:

$NewRegistryLocation = $RegistryLocation.Split("*")
Test-Path -Path $NewRegistryLocation
Run Code Online (Sandbox Code Playgroud)

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

但这有效($NewRegistryLocation变量的值):

Test-Path -Path "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

box*_*dog 5

Split()每次找到你给它的字符时,该方法都会将字符串分成两部分,从而产生一个数组.它不仅仅是从字符串末尾删除字符.

在您的情况下,有很多方法可以解决这个问题:

  1. 如果可能,请不要首先在星号中添加星号
  2. 仅使用数组中的第一项: $NewRegistryLocation = $RegistryLocation.Split("*")[0]
  3. 使用Split-Path(这符合我的意图):$NewRegistryLocation = Split-Path -Path $RegistryLocation -Parent
  4. 使用-replace运算符删除星号:$NewRegistryLocation = $RegistryLocation -replace "\*",""

方法3可能是我推荐的,因为它更健壮,更'强大'.