如何在 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"
}
这很好用,但我更喜欢内联的东西。
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!'}
unless
作为关键字(就像 if
一样),但大多数其他语言的用户都讨厌它。
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!"
}
-not
带有!
的传统替代品吗?我还能以某种方式获得-eq
和-ne
的传统替代品吗?-not
是唯一带有备用的逻辑运算符(请参阅help about_Logical_Operators
),并且运算符不能有别名。!
需要括号的事实。Get-ChildItem -r -inc *.txt | !Test-Path