PowerShell - 如何检查 "Not Contains" 子句?

PowerShell - how to check "Not Contains" clause?

我想检查 windows 服务器中的 PATH 是否包含一些字符串。如果没有,我希望将它添加到 PATH。我想添加这个 "CommonLib" 文件夹。 我尝试在 IF 子句中立即执行此操作:

  > $CommonLib="C:\Program Files\Front\CommonLib"
  > if (($env:Path -split ";").NotContains($CommonLib)) {Write-Host "executing the code"}
    InvalidOperation: Method invocation failed because [System.String] does not contain a method named 'NotContains'.

Contains 被识别(我可以通过执行 ELSE 子句中的代码来做到这一点)但 NotContains 不是。 我该如何解决这个问题? 谢谢!!!

您可以将 not 运算符与 Contains 函数一起使用。

if (!($env:Path -split ";").Contains($CommonLib)) {Write-Host "executing the code"}

else 分支是一个不错的选择。它易于编写和理解。像这样,

if (($env:Path -split ";").Contains($CommonLib)) {
  Write-Host "$CommonLib is in path"
} else {
  Write-Host "$CommonLib is NOT in path"
}

也可以进行测试并将结果存储在变量中。 -not 等逻辑运算符可用于反转其值。测试 if something is something 通常比 someting is not someting 更清楚。像这样,

$CLInPath = ($env:Path -split ";").Contains($CommonLib)
if(-not $CLInPath) {
  Write-Host "$CommonLib is NOT in path"    
}

这避免了 if..else 分支,如果另一个分支不做任何事情,这是需要的。

此处的其他答案为您的问题提供了可行的替代方案和可以说是更好的方法,但要回答您的 具体 问题,您需要使用 -NotContains 运算符:

if (($env:Path -split ";") -NotContains $CommonLib) {
    Write-Host "executing the code"
}