【发布时间】:2020-02-09 06:31:05
【问题描述】:
我了解 Powershell 中的 try-catch-finally,但是否有类似于 Python 的“else”子句,其中代码仅在没有错误时运行?
我正在编写一个脚本,该脚本在一个经常出现故障的站点上使用 invoke-webRequest。我使用 try-catch 来捕获 HTTP 错误。 我还希望只有在 invoke-webRequest 命令成功完成时才运行一段代码。
try{
invoke-WebRequest -URI 'http://flakywebsite.com/site1' -Method GET
invoke-WebRequest -URI 'http://flakywebsite.com/site2' -Method GET
invoke-WebRequest -URI 'http://flakywebsite.com/site3' -Method GET
}
catch{
"This line will execute only if there is an error in the try block"
}
else{
"This line will execute only if there is NOT an error in the try block"
}
finally{
"This code will run regardless of whether there is or is not an error in the try block."
}
我有这个解决方法。它使用 catch 块将通知附加到 $Error 变量:
try{
invoke-WebRequest -URI 'http://flakywebsite.com/site1' -Method GET
invoke-WebRequest -URI 'http://flakywebsite.com/site2' -Method GET
invoke-WebRequest -URI 'http://flakywebsite.com/site3' -Method GET
}
catch{
$Error.add("An error occurred in the try loop."}
}
if($Error[-1] -ne "An error occurred in the try loop."){
"This code will run only if there is NOT an error in the try block.
}
这行得通,但它非常难看。有没有更好的方法在 Powershell 中做到这一点?
【问题讨论】:
-
也许你可以使用
if(!$Error){ "An error didn't occur" }。 -
Invoke-WebRequest中发生的任何错误都应该(取决于你的$ErrorActionPreferenceofc)触发切换到catch块,所以你为什么不把else块中的代码放在下面Invoke-WebRequest?
标签: powershell try-catch