Error action

The ErrorAction parameter and the ErrorActionPreference variable are used to control what happens when a non-terminating error is written.

CmdletBinding:
The ErrorAction parameter is only available if a function declares the CmdletBinding attribute. CmdletBinding is automatically added is automatically added if the Parameter attribute is used.

By default, the ErrorAction is set to continue. Any non-terminating errors will be displayed, but a script or function will continue to run.

If the ErrorAction is set to SilentlyContinue, errors will be added to the automatic variable $error, but the error will not be displayed.

The following function writes a non-terminating error using Write-Error:

function Invoke-Something { 
    [CmdletBinding()] 
    param ( ) 
 
    Write-Error 'Something went wrong' 
} 
Invoke-Something-ErrorAction SilentlyContinue 

The error is written, but hidden from view. The error may be viewed as the latest entry in the $error variable:

PS> $Error[0]
Invoke-Something : Something went wrong
At line:8 char:1
+ Invoke-Something -ErrorAction SilentlyContinue
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,SilentError

If the error action is set to Stop, a non-terminating error becomes a terminating error, for example:

PS> function StopError {
[CmdletBinding()]
param ( )
Write-Error 'Something went wrong'
}
StopError -ErrorAction Stop
StopError : Something went wrong
At line:1 char:1
+ StopError -ErrorAction Stop
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,StopError
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.47.218