Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I negate a condition in PowerShell?

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.

like image 617
Ben McCormack Avatar asked Nov 11 '11 14:11

Ben McCormack


People also ask

How do I stop a query in PowerShell?

Open a PowerShell console session, type exit , and press the Enter key. The PowerShell console will immediately close.

What does :: mean in PowerShell?

Static member operator :: To find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet. The member name may be an expression. PowerShell Copy.

How do I throw an exception in PowerShell?

To create our own exception event, we throw an exception with the throw keyword. This creates a runtime exception that is a terminating error. It's handled by a catch in a calling function or exits the script with a message like this.

Does not match PowerShell?

-match and -nomatch are PowerShell comparison operators that compare a string value against a regular expression. -match returns true if the tested string matches the given regular expression. -notmatch returns true if the tested string does not match the given regular expression.


2 Answers

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!"} 
like image 153
Rynant Avatar answered Sep 23 '22 14:09

Rynant


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

like image 41
Zombo Avatar answered Sep 23 '22 14:09

Zombo