11 December 2013

How to change default error action in Powershell ? (-ErrorAction , -ea)

ErrorAction is a useful parameter, that says what Powershell should ,if error occured, while execute a script.


What  Powershell says about -ErrorAction:

"-ErrorAction[:{SilentlyContinue | Continue | Inquire | Stop)]
    Determines how the cmdlet responds to a non-terminating error    from the command. This parameter works only when the command generates    a debugging message. For example, this parameters works when a command    contains the Write-Error cmdlet.
    The ErrorAction parameter overrides the value of the    $ErrorActionPreference variable for the current command.    Because the default value of the $ErrorActionPreference variable    is Continue, error messages are displayed and execution continues    unless you use the ErrorAction parameter.
    The ErrorAction parameter has no effect on terminating errors (such as    missing data, parameters that are not valid, or insufficient    permissions) that prevent a command from completing successfully.
    Valid values:
        SilentlyContinue. Suppresses the error message and continues        executing the command.
        Continue. Displays the error message and continues executing        the command. "Continue" is the default value.
        Inquire. Displays the error message and prompts you for        confirmation before continuing execution. This value is rarely        used.
        Stop. Displays the error message and stops executing the        command."

Default behave is "Continue",so if shit happens then.. Powershell will happy to carry on and flooded us with errors after errors.
Question is how change this default behave?

SOLUTION
You need set global variable called $ErrorActionPreference to SilentlyContinue , Inquire or Stop (there is Continue  too,but as it is default value )

EXAMPLE:
If you want stop execution of  script as default case,then type this as one of first lines in your amazing script

$ErrorActionPreference = "Stop"



Source: Powershell's command line:  get-help about_commonparameters -full