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.
Open a PowerShell console session, type exit , and press the Enter key. The PowerShell console will immediately close.
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.
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.
-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.
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!"}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With