如何在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"
}

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

374724 次浏览

你用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!"}

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

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


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

使用实例

Powershell也接受C/ c++ /C* not操作符

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

我经常用它,因为我习惯C* 允许代码压缩/简化…
我还发现它更优雅…

如果你不喜欢双括号或者你不想写函数,你可以直接用变量。

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