try, catch doesent seem to work

前端 未结 1 410
清歌不尽
清歌不尽 2020-11-29 11:49

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 sti

相关标签:
1条回答
  • 2020-11-29 12:31

    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.

    0 讨论(0)
提交回复
热议问题