Ben*_*ack 252 windows powershell
如何在PowerShell中否定条件测试?
例如,如果我想检查目录C:\ Code,我可以运行:
if (Test-Path C:\Code){
write "it exists!"
}
Run Code Online (Sandbox Code Playgroud)
有没有办法否定这种情况,例如(非工作):
if (Not (Test-Path C:\Code)){
write "it doesn't exist!"
}
Run Code Online (Sandbox Code Playgroud)
解决方法:
if (Test-Path C:\Code){
}
else {
write "it doesn't exist"
}
Run Code Online (Sandbox Code Playgroud)
这很好,但我更喜欢内联.
Ryn*_*ant 466
你差不多了Not
.它应该是:
if (-Not (Test-Path C:\Code)) {
write "it doesn't exist!"
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用!
:if (!(Test-Path C:\Code)){}
只是为了好玩,你也可以使用按位独占或,虽然它不是最易读/可理解的方法.
if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}
Run Code Online (Sandbox Code Playgroud)
小智 9
如果你像我一样并且不喜欢双括号,你可以使用一个函数
function not ($cm, $pm) {
if (& $cm $pm) {0} else {1}
}
if (not Test-Path C:\Code) {'it does not exist!'}
Run Code Online (Sandbox Code Playgroud)
Powershell 也接受 C/C++/C* not 运算符
if ( !(Test-Path C:\Code) ){ 写“它不存在!” }
我经常使用它是因为我习惯了 C*...
允许代码压缩/简化...
我也发现它更优雅...
小智 6
如果您不喜欢双括号或者不想编写函数,则可以只使用变量。
$path = Test-Path C:\Code
if (!$path) {
write "it doesn't exist!"
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
263627 次 |
最近记录: |