【发布时间】:2015-10-31 12:56:06
【问题描述】:
在 PowerShell 中是否有更简洁且不易出错的方法来检查路径是否不存在?
对于这样一个常见的用例来说,这客观上太冗长了:
if (-not (Test-Path $path)) { ... }
if (!(Test-Path $path)) { ... }
它需要太多的括号并且在检查“不存在”时不是很可读。这也容易出错,因为这样的语句:
if (-not $non_existent_path | Test-Path) { $true } else { $false }
实际上会返回False,而用户可能期望True。
有什么更好的方法来做到这一点?
更新 1:我目前的解决方案是为 exist 和 not-exist 使用别名,如 here 所述。
更新 2: 也可以解决此问题的建议语法是允许以下语法:
if !(expr) { statements* }
if -not (expr) { statements* }
这是 PowerShell 存储库中的相关问题(请投票 ????):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 }
标签: powershell