Trouble using Write-Error

I was recently reading on reasons not to use Write-Host in PowerShell, so I’ve started using Write-Verbose, Write-Warning and Write-Output…but I’m having some issues with the output that I’m getting from Write-Error.

Here is a simple example of it’s use in a script.

1..5 | foreach{
    if ($_ -eq 5){
        Write-Error "Invalid result"
    }
}

When the error show up i get the following.

1..5 | foreach{
    if ($_ -eq 5){
        Write-Error "Invalid result"
    }
} : Invalid result
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

I don’t understand why it displays all of the code above the error. it just makes the output on screen look extremely messy, especially in long script. For example i am currently developing a script to automate our user creation, modification, disabling and deletion process and it is several hundred lines, so if i want to write a non terminating error, I don’t want to see the entire code above it…That’s just silly.

Any suggestions. I thought about using write-warning, however it really is a non terminating error that i want to display…so i’m trying to use best practice.

Thanks

Most of the time, you won’t see that. The only time I can think off offhand is if you paste that code directly into the console (or into the ISE and run it without saving the script first, which amounts to the same thing.)

Normally, you’ll see line that called the script or function that contains the Write-Error command instead. For example:

C:\Source\Temp\test.ps1 : Invalid result
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,test.ps1

Or:

Test-Function : Invalid result
At C:\Source\Temp\test.ps1:10 char:1
+ Test-Function
+ ~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-Function

Thanks

That makes sense, since i was working in the ISE an only executing a section of code instead of the whole script.