windows 如何否定 PowerShell 中的条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8095638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:55:37  来源:igfitidea点击:

How do I negate a condition in PowerShell?

windowspowershell

提问by Ben McCormack

How do I negate a conditional test in PowerShell?

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

For example, if I want to check for the directory C:\Code, I can run:

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

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

Is there a way to negate that condition, e.g. (non-working):

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

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


Workaround:

解决方法

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

This works fine, but I'd prefer something inline.

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

回答by Rynant

You almost had it with Not. It should be:

你几乎拥有它Not。它应该是:

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

You can also use !: if (!(Test-Path C:\Code)){}

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

Just for fun, you could also use bitwise exclusive or, though it's not the most readable/understandable method.

只是为了好玩,您也可以使用按位互斥,或者虽然它不是最易读/易理解的方法。

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

回答by Steven Penny

If you are like me and dislike the double parenthesis, you can use a function

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

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

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

Example

例子

回答by ZEE

Powershell also accept the C/C++/C* not operator

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

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

if ( !(Test-Path C:\Code) ){ 写“它不存在!” }

I use it often because I'm used to C*...
allows code compression/simplification...
I also find it more elegant...

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

回答by Melchior Kannengie?er

if you don't like the double brackets or you don't want to write a function, you can just use a variable.

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

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