尝试,catch 似乎没有用 [英] try, catch doesent seem to work
问题描述
我有以下代码,我认为它可以让我捕获错误,而不是生成错误,写出发生错误".
I have the following code which I thought would allow me to catch an error and instead of generating the error write out "An Error Occurred".
不幸的是,它仍然显示错误无法重新启动计算机:访问被拒绝".
Unfortunately, it still shows the error "Failed to restart the computer: Access is denied" instead.
我知道为什么会发生这种情况,但我希望能够捕获错误并重新格式化.我做错了什么?
I know why this is happening but I want to be able to catch the error and reformat it. What am I doing wrong?
try {
Restart-Computer -ComputerName MFG-KY-PC74 -Force
} catch {
Write-Host "An Error Occurred"
}
推荐答案
在 PowerShell 中存在终止和非终止错误.前者终止脚本执行(如果没有被捕获)并且可以被 try..catch
捕获,后者不终止脚本执行(所以没有什么可捕获的).您收到的错误是非终止错误,因此您需要通过将 -ErrorAction Stop
附加到语句来使其成为终止错误:
In PowerShell there are terminating and non-terminating errors. The former terminate script execution (if not caught) and can be caught by try..catch
, the latter don't terminate script execution (so there's nothing to catch). The error you're receiving is a non-terminating one, so you need to make it a terminating error by appending -ErrorAction Stop
to the statement:
try {
Restart-Computer -ComputerName MFG-KY-PC74 -Force -ErrorAction Stop
} catch {
write-host "An Error Occurred"
}
或者,如果您希望所有错误都变成终止错误,您可以设置 $ErrorActionPreference = "Stop"
.
Alternatively you can set $ErrorActionPreference = "Stop"
if you want all errors to become terminating errors.
参见 这篇文章位于脚本专家博客上,了解更多信息.
See this article on the Scripting Guy blog for more information.
这篇关于尝试,catch 似乎没有用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!