PowerShell Write-Error

1.6k views Asked by At

I have coded a simple Log function which calls cmdlet Write-Error. However, this produces some unexpected behavior. To give you an example:

function foo {
    Param([string]$Msg = "This is an error")
    Write-Error $Msg
}

Calling foo results in the following:

foo: This is an error
At line:1 char:1
+ foo

So, it seems that calling foo (and the cmdlet Write-Error therein), throws an error that PS links to the function foo itself.

What would be the correct way to write a message into the PS error stream but without having it look like an error in the calling function?

I found the answer: The difference is a bit subtle: There is a difference between throwing an error and outputting error messages to the standard error stream. In a try/catch structure throwing an error would jump into the catch block. While using write-error in the try block would just pipe the output into the standard error stream. The following function will not go into the catch block. However, it writes an error message "Hey" into the $error variable and leaves all other attributes empty.

function myErr { try { write-error "Hey" } catch { write-host "Ups" } }

The error message, however, will show that the error occurred in myErr at line 1, char 1.

So okay, I see that this seems to be the standard behavior when calling write-error. I will use write-output then.

1

There are 1 answers

0
Ranadip Dutta On

Instead of this:

function foo {
    Param([string]$Msg = "This is an error")
    Write-Error $Msg
}

Use write-output for it. That is the normal behavior of write-error in PS:

function foo {
    Param([string]$Msg = "This is an error")
    Write-Output $Msg
}