Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

powershell - 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"
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...