Write-Error

The Write-Error command can be used to write non-terminating error messages.

The Write-Error command can be used with nothing more than a message:

Write-Error 'Message' 

Or it might include additional information, such as a category and error ID to aid diagnosis by the person using the script:

Write-Error -Message 'Message' -Category 'InvalidOperation' -ErrorId 'UniqueID' 

The following example shows a non-terminating error that was raised while running a loop:

function Test-Error { 
    for ($i = 0; $i -lt 5; $i++) { 
        Write-Error -Message "Iteration: $i" 
    }
} Test-Error

The error will be displayed five times without stopping execution.

Setting the value of ErrorAction to Stop will cause Write-Error to throw a terminating error, ending the function within the first iteration of the loop:

PS> function Test-Error {
>> [CmdletBinding()]
>> param ( )
>>
>> for ($i = 0; $i -lt 5; $i++) {

>> Write-Error -Message "Iteration: $i"
>> }
>> }
>>

PS> Test-Error -ErrorAction Stop
Test-Error : Iteration: 0
At line:1 char:1
+ Test-Error -ErrorAction Stop
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Error

Alternatively, the error might be silent (SilentlyContinue) or ignored (Ignore), depending on the context in which the error appears.

Setting the ErrorActionPreference variable (either globally or within the function scope) will have the same effect on the Write-Error command.

..................Content has been hidden....................

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