PowerShell Error Variables

Today, you will learn about PowerShell Error Variables, which are very important for PowerShell administrators or developers. In this tutorial, I will explain how to use PowerShell error variables.

The $Error variable in PowerShell is an automatic array that stores information about the most recent errors in the current session, with the latest error at index 0. You can access and handle these errors using a try-catch block, where the catch block can output the error message and detailed error information stored in $Error[0].

What is the $Error Variable in PowerShell?

The $Error variable in PowerShell is an automatic variable that stores information about the most recent errors that have occurred in the current session. This variable is an array, with the most recent error at index 0. It helps diagnose issues and understand what went wrong during script execution.

Here is an example.

# Example: Accessing the most recent error
try {
    Get-Item "C:\NonExistentFile.txt" -ErrorAction Stop
} catch {
    Write-Host "Error occurred: $($_.Exception.Message)"
    Write-Host "Detailed Error: $($_.Exception)"
}

In the above example, the $Error variable captures the error generated by attempting to access a non-existent file. The catch block then outputs the error message and detailed error information.

Here is the output in the screenshot below:

PowerShell Error Variables

Check out PowerShell Static Variables

Using -ErrorVariable Parameter

PowerShell commands often include the -ErrorVariable parameter, which allows you to specify a variable to store errors generated by that specific command. This is particularly useful for isolating errors and handling them separately.

Let me show you an example.

# Example: Using -ErrorVariable
$errVar = $null
Get-Item "C:\NonExistentFile.txt" -ErrorVariable errVar

if ($errVar) {
    Write-Host "Error captured in errVar: $($errVar[0].Exception.Message)"
}

In this example, the error is stored in the custom variable $errVar instead of the global $Error array. This method helps in managing errors more precisely within scripts.

Here is the output in the screenshot below:

Error Variable in PowerShell

Check out PowerShell Private Variables

Append Errors with -ErrorVariable

By default, in PowerShell, you can use -ErrorVariable overwrites the variable with the new error. However, you can append errors to the existing variable by prefixing the variable name with a + sign.

# Example: Appending errors
$errVar = $null
Get-Item "C:\NonExistentFile.txt" -ErrorVariable +errVar
Get-Item "C:\AnotherNonExistentFile.txt" -ErrorVariable +errVar

if ($errVar) {
    foreach ($error in $errVar) {
        Write-Host "Captured Error: $($error.Exception.Message)"
    }
}

This example demonstrates how to capture multiple errors in a single variable, making it easier to handle and review all errors that occur during script execution.

Read Generate Random Numbers in PowerShell

PowerShell Error Variables Real-World Example: Automating File Operations

Consider a scenario where you need to automate the process of copying files from one directory to another in PowerShell. You want to ensure that any errors encountered during the copy process are logged and handled appropriately.

# Real-world example: Copying files with error handling
$sourceDir = "C:\Source"
$destDir = "C:\Destination"
$errorLog = "C:\ErrorLog.txt"
$errVar = $null

# Ensure destination directory exists
if (-not (Test-Path $destDir)) {
    New-Item -ItemType Directory -Path $destDir
}

# Copy files with error handling
Get-ChildItem $sourceDir | ForEach-Object {
    try {
        Copy-Item -Path $_.FullName -Destination $destDir -ErrorVariable +errVar
    } catch {
        Write-Host "Error copying file: $($_.Exception.Message)"
    }
}

# Log errors if any
if ($errVar) {
    $errVar | ForEach-Object {
        Add-Content -Path $errorLog -Value "Error copying file: $($_.Exception.Message)"
    }
    Write-Host "Errors logged to $errorLog"
} else {
    Write-Host "All files copied successfully."
}

In this script, files are copied from the source directory to the destination directory. Any errors encountered during the copy process are captured in the $errVar variable and logged to a file. This ensures that the script can continue running even if some files fail to copy, and provides a detailed log for troubleshooting.

Conclusion

PowerShell error variables are useful for managing and handling errors in your scripts. By using the $Error variable and the -ErrorVariable parameter, you can capture, manage, and log errors effectively. In this tutorial, I have explained how to use the error variables in PowerShell with examples.

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.