try, catch doesent seem to work

2019-01-06 23:18发布

问题:

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

回答1:

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.