Windows – How to negate a condition in PowerShell

powershellwindows

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.

Best Answer

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