ChatGPT解决这个技术问题 Extra ChatGPT

如何否定 PowerShell 中的条件?

如何在 PowerShell 中否定条件测试?

例如,如果我想检查目录 C:\Code,我可以运行:

if (Test-Path C:\Code){
  write "it exists!"
}

有没有办法否定这种情况,例如(非工作):

if (Not (Test-Path C:\Code)){
  write "it doesn't exist!"
}

解决方法:

if (Test-Path C:\Code){
}
else {
  write "it doesn't exist"
}

这很好用,但我更喜欢内联的东西。


R
Rynant

Not 几乎可以满足您的要求。它应该是:

if (-Not (Test-Path C:\Code)) {
    write "it doesn't exist!"
} 

您也可以使用 !if (!(Test-Path C:\Code)){}

只是为了好玩,您也可以使用按位排他或,尽管它不是最易读/易理解的方法。

if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}

有趣的是,那么 -not 带有 ! 的传统替代品吗?我还能以某种方式获得 -eq-ne 的传统替代品吗?
不,-not 是唯一带有备用的逻辑运算符(请参阅 help about_Logical_Operators),并且运算符不能有别名。
谢谢,我错过了使用 ! 需要括号的事实。
术语“!Test-Path”未被识别为 cmdlet 的名称 ... :)
我希望有更好的方法来支持管道。例如Get-ChildItem -r -inc *.txt | !Test-Path
Z
Zombo

如果你和我一样不喜欢双括号,你可以使用一个函数

function not ($cm, $pm) {
  if (& $cm $pm) {0} else {1}
}

if (not Test-Path C:\Code) {'it does not exist!'}

Example


我喜欢这个,但可能无法在任何地方使用这个 not 实现(例如 not Test-Path -path C:\Code 不起作用)。另请参阅此相关的 post
Perl 有一个更合乎逻辑的,在 Vulcan 意义上,成语,称为除非,它被写成一个函数。作为半个 Vulcan,我更喜欢它,并且在 C# 中作为函数实现了它,在 C 和 C++ 中作为宏实现了它。
@DavidA.Gray Ruby 将 unless 作为关键字(就像 if 一样),但大多数其他语言的用户都讨厌它。
s
ssilas777

Powershell 也接受 C/C++/C* not 运算符

 if ( !(Test-Path C:\Code) ){ write "it doesn't exist!" }

我经常使用它,因为我习惯了 C*... 允许代码压缩/简化... 我也觉得它更优雅...


M
Melchior

如果你不喜欢双括号或者你不想写一个函数,你可以只使用一个变量。

$path = Test-Path C:\Code
if (!$path) {
    write "it doesn't exist!"
}