在我的powershell脚本中,我有以下一行:
$DirectoryInfo = Get-ChildItem $PathLog | Where-Object { $_.PSIsContainer }
从变量$PathLog
中给出的路径中读取一些数据。但我意识到即使Get-ChildItem
命令失败(例如,$PathLog
中的给定路径不存在),并且错误被写入shell,脚本仍会继续。
如何检查此Get-ChildItem
是否成功?我想用它来触发一个if
子句,如下所示,在那一刻停止脚本:
if (???) {
"There was an error"
return
}
放入括号中的内容是什么?怎么办呢?
答案 0 :(得分:1)
你可以使用Try/Catch
块来捕捉@Beatcracker回答的错误,或者如果你真的关心它是否成功,你可以使用$?
。
$?
包含上次操作的执行状态。它包含 如果上一次操作成功则为TRUE,如果失败则为FALSE。
使用$?
时,我通常也会隐藏Get-ChildItem
的错误,因此我已添加-ErrorAction SilentlyContinue
来处理示例中的错误。
$DirectoryInfo = Get-ChildItem c:\DoesntExist -ErrorAction SilentlyContinue | Where-Object { $_.PSIsContainer }
if($?) {
"It worked!"
} else {
"It failed! :-("
}
答案 1 :(得分:1)
A"轻量级" try/catch/finally
的替代是$?
自动变量。如果上一个命令失败,则其值为$false
:
Get-ChildItem F:\non\existing\path -ErrorAction SilentlyContinue
if(-not $?)
{
throw "Get-ChildItem failed"
}
答案 2 :(得分:0)
使用Try/Catch
阻止和-ErrorAction Stop
:
try {
$DirectoryInfo = Get-ChildItem $PathLog -ErrorAction Stop | Where-Object { $_.PSIsContainer }
} catch {
Write-Error "There was an error"
return
}
答案 3 :(得分:0)
根据您要解析的内容以及您是否对异常感兴趣,这可能会有所帮助:
(Get-ChildItem Env:\MYENVKEY -ErrorAction SilentlyContinue).Value | %{ IF($null -eq $_) { $result="not found" } ELSE { $result=$_ } };
它将尝试获取值并安全地处理是否找到它。