Is there a more concise and less error-prone way in PowerShell to check if a path DOES NOT exist?
This is objectively too verbose for such a common use case:
if (-not (Test-Path $path)) { ... }
if (!(Test-Path $path)) { ... }
It needs too many parenthesis and is not very readable when checking for "not exist". It's also error-prone because a statement like:
if (-not $non_existent_path | Test-Path) { $true } else { $false }
will actually return False
, when the user may expect True
.
What is a better way to do this?
Update 1: My current solution is to use aliases for exist
and not-exist
as explained here.
Update 2: A proposed syntax that will also fix this is to allow the following grammar:
if !(expr) { statements* }
if -not (expr) { statements* }
Here's the related issue in PowerShell repository (please vote up π): https://github.com/PowerShell/PowerShell/issues/1970
try{ Test-Path -EA Stop $path; #stuff to do if found } catch { # stuff to do if not found }
β Burgundy