Write-Error

Understanding Write-Error in PowerShell

Welcome back to Wahmans PowerShell blog! Today, we will explore a fundamental yet powerful cmdlet in PowerShell: Write-Error. This cmdlet is used to generate error messages by writing them to the error stream. Whether you are building scripts for automation or writing modules, knowing how to effectively use Write-Error is essential for robust error handling and communication with the user.

What does Write-Error do?

According to the official Microsoft documentation, Write-Error “Writes an object to the error stream.” This means you can generate custom error messages that can be handled by error processing features in PowerShell, such as try/catch blocks or error logs.

Example 1: Basic Usage

A simple example is outputting an error message when a condition is not met.

if (-not (Test-Path "C:\ImportantFile.txt")) {
    Write-Error "The required file 'C:\ImportantFile.txt' does not exist."
}

This snippet checks for a file, and if it doesn’t exist, it displays a clear error message on the error stream.

Example 2: Using Write-Error in a Function

Let’s create a function that checks user input and writes an error if the input is invalid.

function Get-Squared {
    param (
        [Parameter(Mandatory)]
        [int]$Number
    )

    if ($Number -lt 0) {
        Write-Error "Negative numbers are not supported."
        return
    }

    return $Number * $Number
}

A developer calling this function with a negative number receives a controlled error message.

Example 3: Throw vs Write-Error

While throw terminates execution, Write-Error does not unless $ErrorActionPreference is set to “Stop”. Here we show how it interacts with try/catch when ErrorActionPreference is changed:

$ErrorActionPreference = "Stop"
try {
    Write-Error "This is a terminating error now."
} catch {
    Write-Host "Caught an error: $($_.Exception.Message)"
}

This is useful when you want to treat Write-Error messages as critical and halt execution accordingly.

Example 4: Custom Error Records

For advanced error handling, you can construct custom error records:

$exception = New-Object System.Exception "Custom exception message."
$errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, "CustomID", "InvalidArgument", $null
Write-Error $errorRecord

This strategy is helpful when building tools or modules where structured error information is necessary for consumers to react accordingly.

Conclusion

Whether you need to inform users of incorrect inputs, warn about missing files, or implement structured error handling for your advanced modules—Write-Error is a versatile cmdlet at your disposal. Use it wisely to make your scripts more user-friendly and maintainable.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *