PowerShell Beginner’s Guide – Error Handling Methods

In this post we will be going through different error handling methods available in PowerShell and examples on using these.

Error handling is very usefully to learn, it allow us to write scripts that can export / write errors to a log or completed certain task if a part of the script fails.

There are also two types of errors Non-Terminating and Terminating, Non-Terminating error can cause issue when using certain error handling methods, we will cover this more when we get to the try-catch section.

PowerShell has a few different ways to handle errors gracefully:

  1. Error: When using $error, we can return error messages that are stored in the default variable.
  2. Error Action Preferences: PowerShell provides different error action preferences like Stop, Continue SilentlyContinue…, allowing how to control the behavior when an error occurs.
  3. ErrorVariable: Creates a new variable to store error messages, this can then be used later to output or logging.
  4. Try-Catch: The try block run the code specified and in the event of an error the catch block catches and handles those errors. This allows for us to control how errors are managed within the script.
  5. Finally: PowerShell includes a finally block which executes regardless of whether an error occurs or not. This is useful for performing cleanup tasks or finalizing operations, like send a log file or email .

By using these features, PowerShell allows handle errors more effectively.

$Error variable

$Error is the default variable that all errors are written to, we can call this in side a script and use the index operator [0], zero returns the latest error.

I would generally not use this method but it can be usefully for simpler scripts that we just want to export the error while the script runs.

Below are some examples of using $error.

$Error[0]
Error Variable

We can also call specific properties to export more specific error propertied. We can view the properties by using Get-Member

$Error | Get-Member
Error variable additional properties

To chose a error propriety we put dot and exception.

Error variable exception

ErrorAction Parameter

ErrorAction Allows us to specify the action PowerShell should take when an error occurs. This is done using -ErrrorAction parameter.

I would generally only use this when I need to set an error to terminate and I am using error variable and don’t want to write the error to the PowerShell console.

Below example shows setting error action to continue silently.

Get-ChildItem -Path 'C:\Folder_Does_Not_Exist' -ErrorAction SilentlyContinue
Error action

ErrorVariable

ErrorVariable is used to captures error information into a custom variable, this can then be used to output to a log file or out to the PowerShell console.

This is a good method to create multiple errors objects and write a log file that outputs errors while the script runs.

Below example we are silencing the error and then adding it to a new a variable.

Error variable
Get-ChildItem -Path 'C:\Folder_Does_Not_Exist' -ErrorVariable MyErrors

$MyErrors

Below example shows exporting to a txt file.

Error variable out to file
Get-ChildItem -Path 'C:\Folder_Does_Not_Exist' -ErrorVariable MyErrors -ErrorAction SilentlyContinue

$MyErrors.Exception | Out-File C:\temp\Logs\Error_log.txt -Append

Try-Catch-Finally

The last method we will cover is try catch method, this method allows us to catch and handle errors gracefully within a script and then specify code to run in case of an error.

Try catch is a more complex error handling method as it allow for additional code or actions to be perform that can be as simple as out putting error or running additional command that could be use to fix or alert for issues while the script is running.

When using try catch the error need to be a terminating error or the catch wont work. Get-ChildItem isn’t a terminating error, due to this we will be using -ErrorAction stop to make it terminate.

Below examples show the difference when using a terminating and non-terminating error with try catch.

Try Catch terminating vs non
try {
    Get-ChildItem -Path 'C:\Folder_Does_Not_Exist'  -ErrorAction Stop
} 
catch {
    Write-Host "An error has occorred" $Error[0].ErrorDetails"
} 

We can add finally to the try catch to run a command at the end whether or not there is an error.

This can be useful if we want the script to do something like copy the log file or send a email or notification the script has completed.

Below example will remove the log file after the script has completed.

Try Catch Finally
try {
    Get-ChildItem -Path 'C:\Folder_Does_Not_Exist' -ErrorAction Stop
} 
catch {
    Write-Host "An error has occorred" $Error[0].ErrorDetails
} Finally { 
    Remove-Item C:\temp\Logs\Error_log.txt -Verbose
}

The above methods shows the different way to handle errors in PowerShell, being able to use error handling in scripts is very useful skill to learn and helps with more complex scripts.

PowerShell Beginner’s Guide – Using IF Else Statements

In this post we will be going through using if else statements.

If else statement in PowerShell evaluates a condition and executes code if the condition is true. If the condition is false, alternative code is executed.

If else can also be nested to create more complex scripts that handle multiple conditions and execute specific code for each condition.

If else follows the below format

if (condition) {
    # code to execute if condition is true
} 
else {
    # code to execute if condition is false
}

If Statement

We will first go through using a single if statement, when using a if the part between the two () is the conditions which needs to be checked.

When using an if without an operator (eq, like, gt…..), the if will check that the variable is not empty.

The below shows the difference between the if statement when there is a value and no value.

When using an operator we can specify if the value matches then run the code.

$con = "True"
if($con -eq "True"){
    Write-Host "Con is true" -ForegroundColor Green
}

If Else

Next we will go through using if and else. Adding else is a way to executed code if none of the conditions are meet.

$con = "True"
if($con -eq "True"){
    Write-Host "Con is true" -ForegroundColor Green
}
else
{
    Write-Host "Con is false" -ForegroundColor Red
}

We can add an elseif to add another condition, there is no limit to how many can be added but it can be a bit messy if there are two many if elseif’s. Also the first condition that is meet is will stop the rest from being tested.

$con = "True"
if($con -eq "True"){
    Write-Host "Con is true" -ForegroundColor Green
}
elseif ($con -eq "False") {
    Write-Host "Con is false" -ForegroundColor Red
}
else
{
    Write-Host "Con does not meet condition" -ForegroundColor Yellow
}

If with additional operator

We can test multiple conditions by using different operator in the if statement. In the below we are using the -and operator to check that condition one is true and condition two is greater than 3

We can also use -or operator which allows for us to specify two expressions and returns true if either one of them is true.

$con1 = "True"
$con2 = "5"
if ($con1 -eq "True" -or $con2 -gt "6"){Write-Host "Condition are meet" -ForegroundColor Green}

If Null

We can also check for Null values in If statements, to check if a variable or result is null we use the $null variable.

The $null variable must be on the left side of the statement as if it not PowerShell may not

Using if statements in your PowerShell scripts creates a lot of possibilities for creating dynamic and responsive automation. They can be a bit confusing at the start but with a bit of practice and experimentation, if statements become powerful tools in your scripting.