Search code examples
powershellwrite-error

Writing to error stream in Powershell using Write-Error


Why isn't Powershell's Write-Error cmdlet working for me? My output doesn't look like the examples in the documentation:

PS C:\> Write-Error "This is an error"
Write-Error "This is an error" : This is an error
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

I had been expecting output similar to Write-Warning:

PS H:\> Write-Warning "This is a warning"
WARNING: This is a warning

From the Write-Error and about_preference_variables documentation I thought I should not see any exceptions?

PS H:\> Get-Help About_Preference_Variables

$ErrorActionPreference
----------------------

...

        PS> $erroractionpreference                      
        Continue        # Display the value of the preference.                

        PS> write-error "Hello, World"                  
                                # Generate a non-terminating error.

        write-error "Hello, World" : Hello, World       
                                # The error message is displayed and
                                  execution continues.

        PS> write-error "Hello, World" -ErrorAction:SilentlyContinue
                                # Use the ErrorAction parameter with a 
                                  value of "SilentlyContinue".
        PS>                                             
                                # The error message is not displayed and
                                  execution continues.

Solution

  • To get output similar to write-warning, you can do this:

    $Host.UI.WriteErrorLine("This is an error")
    

    (props to Chris Sears for this answer)