07-21-2023, 11:09 AM
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 👍):
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](
[To see links please register 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 👍):
[To see links please register here]