为什么 -like 不起作用但 -match 起作用?

Why is -like not working but -match does?

我从这里得到这个脚本,它可以用于卸载应用程序,但只有在前两行使用 -match 而不是 -like 时,即使我使用了整个应用程序名称.

应用程序的名称包含版本,所以我想在脚本中使用通配符来支持 "MyApp 2.4.1" 等。谢谢!

$uninstall32 = gci "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" | 
     foreach { gp $_.PSPath } | ? { $_ -like "MyApp*" } | select UninstallString

$uninstall64 = gci "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | 
     foreach { gp $_.PSPath } | ? { $_ -like "MyApp*" } | select UninstallString

if ($uninstall64) {
   $uninstall64 = $uninstall64.UninstallString -Replace "msiexec.exe","" -Replace "/I","" -Replace "/X",""
   $uninstall64 = $uninstall64.Trim()

   Write "Uninstalling..."
   start-process "msiexec.exe" -arg "/X $uninstall64 /qb" -Wait
}

if ($uninstall32) {
   $uninstall32 = $uninstall32.UninstallString -Replace "msiexec.exe","" -Replace "/I","" -Replace "/X",""
   $uninstall32 = $uninstall32.Trim()

   Write "Uninstalling..."
   start-process "msiexec.exe" -arg "/X $uninstall32 /qb" -Wait
}

考虑以下字符串“MyApp 2.3.4”,同时将查看您引用的两个示例之间的重要区别:

  • 喜欢? { $_ -like "MyApp*" }
  • 匹配? { $_ -match "MyApp*" }

-Like 正在寻找字符串 starting with "MyApp" 后跟任何内容。 -Match 正在查找后跟任意字符的文本 "MyApp"。 -Like 会失败,因为前面有一个 space。 -Match 将 "MyApp*" 视为查找 "MyApp" 后跟任意字符的正则表达式字符串。在这种情况下,它不关心它匹配的 space 。我怀疑 -match 如果你也改变它 ? { $_ -match "^MyApp*" } 会失败,因为插入符号表示字符串的开头。

如果您希望 -like 在这种情况下工作,您应该将其更改为 ? { $_ -like "*MyApp*" }

重要

虽然我对您的比较无效的原因是正确的 首先解决了这个问题发生在您身上的原因。

Get-ItemProperty 生成对象,而不是字符串。检查 DisplayName 属性 而不是对象本身。您还应该扩展卸载字符串,这样您以后就不需要使用$uninstall64.UninstallString

$uninstall64 = gci "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | 
                 foreach { gp $_.PSPath } |
                 ? { $_<b>.DisplayName</b> -like "MyApp*" } |
                 select <b>-Expand</b> UninstallString