When should I use Write-Error vs. Throw? Terminating vs. non-terminating errors

前端 未结 6 1667
别跟我提以往
别跟我提以往 2020-11-28 03:55

Looking at a Get-WebFile script over on PoshCode, http://poshcode.org/3226, I noticed this strange-to-me contraption:

$URL_Format_Error = [string]\"...\"
Wri         


        
6条回答
  •  醉梦人生
    2020-11-28 04:14

    Addition to Andy Arismendi's answer:

    Whether Write-Error terminates the process or not depends on the $ErrorActionPreference setting.

    For non-trivial scripts, $ErrorActionPreference = "Stop" is a recommended setting to fail fast.

    "PowerShell’s default behaviour with respect to errors, which is to continue on error ...feels very VB6 “On Error Resume Next”-ish"

    (from http://codebetter.com/jameskovacs/2010/02/25/the-exec-problem/)

    However, it makes Write-Error calls terminating.

    To use Write-Error as a non-terminating command regardless of other environment settings, you can use common parameter -ErrorAction with value Continue:

     Write-Error "Error Message" -ErrorAction:Continue
    

提交回复
热议问题