How do I negate a condition in PowerShell?

后端 未结 4 1774
轻奢々
轻奢々 2020-12-23 08:37

How do I negate a conditional test in PowerShell?

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

if (Test-Path C:\\Code){
  w         


        
相关标签:
4条回答
  • 2020-12-23 09:16

    You almost had it with Not. It should be:

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

    You can also use !: 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!"}
    
    0 讨论(0)
  • 2020-12-23 09:16

    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

    0 讨论(0)
  • 2020-12-23 09:18

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

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

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

    0 讨论(0)
  • 2020-12-23 09:28

    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!"
    }
    
    0 讨论(0)
提交回复
热议问题