如何在PowerShell中否定一个条件?

19 浏览
0 Comments

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

这个方法可以正常工作,但我更喜欢一些内联方法。

admin 更改状态以发布 2023年5月22日
0
0 Comments

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

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

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

0
0 Comments

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

0