Dave
Dave

Reputation: 3717

Why does Write-Error terminate the script?

Everything I read on the web tells me that Write-Error writes to the error stream, but does not terminate the script, and yet when the following script is run it clearly does terminate the script.

Write-Error "This should not terminate the script..."
Write-Information "... and it hasn't"

The output is:

D:\MyBitsAndBobs\writeerrortest.ps1 : This should not terminate the script...
At D:\MyBitsAndBobs\writeerrortest.ps1:3 char:1
+ Write-Error "This should not terminate the script..."
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,writeerrortest.ps1

The message ".. and it doesn't" is clearly never executed. Can anyone shed any light on this apparently unexpected behaviour?

Upvotes: 2

Views: 1766

Answers (2)

AdamL
AdamL

Reputation: 13141

Take a look at your $ErrorActionPreference variable. By default it is set to Continue and indeed does not terminate the script. In your case it's probably set to Stop. Change it to $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue and run your script again. There are more settings than these two, explore them.

Upvotes: 0

Theo
Theo

Reputation: 61028

This has to do with the way Write-Information by default works.

As per the docs:

The $InformationPreference preference variable value determines whether the message you provide to Write-Information is displayed at the expected point in a script's operation. Because the default value of this variable is SilentlyContinue, by default, informational messages are not shown. If you don't want to change the value of $InformationPreference, you can override its value by adding the InformationAction common parameter to your command.

So in your case, either change Write-Information to Write-Host or use:

Write-Error "This should not terminate the script..."
Write-Information "... and it hasn't" -InformationAction Continue

Output:

Write-Error "This should not terminate the script..."
Write-information "... and it hasn't" -InformationAction Continue : This should not terminate the script...
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

... and it hasn't

Upvotes: 1

Related Questions