Trouble using Write-Error

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of JohnRock Bilodeau JohnRock Bilodeau 2 years, 4 months ago.

  • Author
    Posts
  • #17582
    Profile photo of JohnRock Bilodeau
    JohnRock Bilodeau
    Participant

    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

  • #17584
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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
    
  • #17585
    Profile photo of JohnRock Bilodeau
    JohnRock Bilodeau
    Participant

    Thanks

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

You must be logged in to reply to this topic.