Why is Write-Error displaying all code above it?

1.2k views Asked by At

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,

1

There are 1 answers

0
Keith Hill On

You need to use Write-Error to output non-terminating errors. However, if you want the error output to be less verbose, you can set the $ErrorView variable to CategoryView e.g.:

64> $ErrorView = 'CategoryView'
65> 1..5 | foreach{
>>>     if ($_ -eq 5){
>>>         Write-Error "Invalid result"
>>>     }
>>> }
>>>
NotSpecified: (:) [Write-Error], WriteErrorException