360

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ben McCormack
  • 32,086
  • 48
  • 148
  • 223

4 Answers4

656

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!"}
Rynant
  • 23,153
  • 5
  • 57
  • 71
13

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

ssilas777
  • 9,672
  • 4
  • 45
  • 68
ZEE
  • 2,931
  • 5
  • 35
  • 47
10

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

Zombo
  • 1
  • 62
  • 391
  • 407
  • 1
    I like this, but probably can't use this `not` implementation everywhere (for example `not Test-Path -path C:\Code` won't work). See also this related [post](http://stackoverflow.com/q/31888580/450913). – orad Aug 13 '15 at 13:06
  • 2
    Perl has a more logical, in the Vulcan sense, idiom, called Unless, which is written as a function. Being half Vulcan, I prefer it, and have implemented it in both C#, as a function, and in C and C++, as a macro. – David A. Gray May 30 '18 at 06:44
  • 1
    @DavidA.Gray Ruby has `unless` as keyword (just like `if`) but most user from other languages hate it. – Franklin Yu Nov 27 '18 at 05:09
6

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!"
}
Melchior
  • 105
  • 2
  • 9