Write Error - PowerShell
Overview
The Write-Error
command in PowerShell allows you to write an error message to the console, redirect it to a variable, or log it to a file. It’s commonly used for handling exceptions, providing diagnostic information, or generating controlled errors for testing purposes.
Syntax
Write-Error [-Message] <string> [-ErrorId] <string> [-Category] <System.Management.Automation.ErrorCategory> [-Exception] <System.Exception> [-Source] <string> [-TargetObject] <object> [-Verbose] [-WarningAction] <System.Management.Automation.ActionPreference>
Options/Flags
| Option/Flag | Description | Default Value |
|—|—|—|
| -Message
| The error message to write. | None |
| -ErrorId
| A unique identifier for the error. | None |
| -Category
| The category of the error. Valid values: Error, Warning, Information, Verbose, Debug. | Error |
| -Exception
| An Exception object associated with the error. | None |
| -Source
| The source of the error. | Current script name |
| -TargetObject
| The target object associated with the error. | None |
| -Verbose
| Displays the error message in verbose mode. | False |
| -WarningAction
| Controls how warnings are handled. Valid values: Continue, Inquire, SilentlyContinue, Stop. | Continue |
Examples
Example 1: Writing a simple error message
Write-Error "An error occurred."
Example 2: Writing an error with an error ID and category
Write-Error -Message "File not found." -ErrorId "FileNotFound" -Category Error
Example 3: Writing an error to a file
Write-Error -Message "Error log" | Out-File error.log
Common Issues
- Ambiguous error messages: Make sure error messages are clear and informative.
- Overuse of error messages: Avoid bombarding users with excessive errors.
- Not handling errors correctly: Use
-ErrorAction
or-Exception
to handle errors programmatically.
Integration
-Exception
can be used to capture and log exception details.Write-Error
can be combined withIf
andTry/Catch
blocks for conditional error handling.- It can be used in conjunction with
Tee-Object
to simultaneously display and log errors.
Related Commands
Throw
Write-Error
Write-Warning
Get-Error