Hi,
This link http://technet.microsoft.com/library/hh849962.aspx indicates that Write-Error is a non-terminating error.
In this example script, why isn’t the end block called?
begin {
"Script beginning..."
}
process {
:abort foreach ($num in $input) {
$num
if ($num -gt 3) {
Write-Error "ERROR: Aborting..."
break abort
}
}
}
end {
"Script ending..."
}
I’ve invoked the script with:
1..5 | myscript
and walked through it line-by-line in the debugger.
As soon as it hit Write-Error, it barfs; it doesn’t even hit the break statement.
It certainly seems to me that Write-Error is not working as documented.
BTW, PS V2
Write-Error is non-terminating. Â Here’s an example:
PS C:\> 1..5 | % {'Begin'} {if ($_ -ge 3) {Write-Error 'Whoops'} else {$_}} {'End'}
Begin
1
2
Whoops
At line:1 char:20
+ 1..5 | % {'Begin'} {if ($_ -ge 3) {Write-Error 'Whoops'} else {$_}} {'End'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
Whoops
At line:1 char:20
+ 1..5 | % {'Begin'} {if ($_ -ge 3) {Write-Error 'Whoops'} else {$_}} {'End'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
Whoops
At line:1 char:20
+ 1..5 | % {'Begin'} {if ($_ -ge 3) {Write-Error 'Whoops'} else {$_}} {'End'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
End
Pay attention to how this executes. Â Even through I output an error to the console, the pipeline values continue to process, so I get 3 errors, one after another.
If it was terminating, you’d see this:
PS C:\> 1..5 | % {'Begin'} {if ($_ -ge 3) {throw 'Whoops'} else {$_}} {'End'}
Begin
1
2
Whoops
At line:1 char:36
+ 1..5 | % {'Begin'} {if ($_ -ge 3) {throw 'Whoops'} else {$_}} {'End'}
+ ~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Whoops:String) [], RuntimeException
+ FullyQualifiedErrorId : Whoops
Hi Poshoholic,
Thanks for your reply. Â Much appreciated.
I tried both your and my original script in:
- PowerGUI Script Editor on my desktop
- PowerGUI Script Editor on our server
- Powershell console on our server
Both scripts worked as expected (as you posted) for #1 and #3. Â In #2, I got the behaviour described in my post (halt on Write-Error).
I must conclude that the PowerGUI installation on our server is corrupted somehow? Â I’ll try a reinstall, and will be careful re: the plugins I install.
In the future, I’ll test my scripts in the Powershell console before posting.
Apologies for the false alarm, and thanks again for the reply.
Regards,
Scott