Write-Error

Write-Error in PowerShell

Write-Error writes an error message to PowerShell’s error stream.

By default, it creates a non-terminating error. That means PowerShell displays the error, but usually continues with the next command.

Write-Error "The file could not be found."

Write-Output "The script continued."

Typical result:

Write-Error: The file could not be found.
The script continued.

Make it terminating

Use:

-ErrorAction Stop

Example:

Write-Error "The file could not be found." -ErrorAction Stop

Write-Output "This line will not run."

Now the error stops normal execution.

Use with try/catch

try {
    Write-Error "The server is unavailable." -ErrorAction Stop
}
catch {
    Write-Warning "The error was caught."
    Write-Warning $_.Exception.Message
}

Possible output:

WARNING: The error was caught.
WARNING: The server is unavailable.

Without -ErrorAction Stop, the catch block normally does not run because Write-Error is non-terminating by default.

Inside a function

function Get-LabFile {
    param(
        [string]$Path
    )

    if (-not (Test-Path -Path $Path)) {
        Write-Error "The file '$Path' does not exist."
        return
    }

    Get-Content -Path $Path
}

Call:

Get-LabFile -Path ".\missing.txt"

Error details

Write-Error can provide more structured information:

Write-Error `
    -Message "The configuration file is missing." `
    -Category ObjectNotFound `
    -ErrorId "ConfigFileMissing" `
    -TargetObject ".\config.json"

This creates an error record containing:

  • Message
  • Error category
  • Error ID
  • Target object

$Error

Errors written by Write-Error are normally stored in the automatic $Error variable.

Write-Error "Testing error storage"

$Error[0]

$Error[0] is the most recent error.

Write-Error versus throw

Write-Error "A problem occurred"
  • Non-terminating by default
  • Usually continues
  • Can be changed with -ErrorAction Stop
throw "A serious problem occurred"
  • Terminating
  • Stops execution immediately unless caught

Write-Error versus other output commands

CommandPurpose
Write-OutputSends normal data to the success pipeline
Write-WarningDisplays a warning
Write-VerboseDisplays detailed information when -Verbose is used
Write-ErrorWrites an error record
throwCreates a terminating exception

A useful rule:

Use Write-Error when an operation has failed but the caller may decide whether execution should continue. Use throw when the operation cannot safely continue.

Leave a Reply