How do I negate a condition in PowerShell?

WindowsPowershell

Windows Problem Overview


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){
  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.

Windows Solutions


Solution 1 - Windows

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!"}

Solution 2 - Windows

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

Solution 3 - Windows

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...

Solution 4 - Windows

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!"
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen McCormackView Question on Stackoverflow
Solution 1 - WindowsRynantView Answer on Stackoverflow
Solution 2 - WindowsZomboView Answer on Stackoverflow
Solution 3 - WindowsZEEView Answer on Stackoverflow
Solution 4 - WindowsMelchiorView Answer on Stackoverflow