PDQ.com mobilePDQ.com desktop
Support

Error Handling With PowerShell

Jordan HammondJordan Hammond
·

If you are like me, not only have you never made an error in your script, but all external forces that are out of your control also always work as intended... Putting a small pause on the sarcasm, what do people without the magic PowerShell touch do? They embark in the ancient battle that has gone on for generations called error handling

PowerShell Error Handling Example

Error handling with PowerShell helps ensure that an unexpected exception does not let a script continue to cause issues. Let’s take a look at a script that will make sure only cool people have access to all the cool stuff.

$GroupMembership = Get-ADGroupMember -Identity “Cool Users”

$UpdatedCoolList = Get-Content \\FileShare\Location\CoolPeople.csv
Foreach($Person in $GroupMembership){

     If($UpdatedCoolList -notcontains $Person){

         Remove-ADGRoupMember -Identity "Cool Users" -User $Person

     }

}

Works great! However, Kris Powell has found out about the cool list, and in anger at being left off the list, he performs an action that proves we are right to keep him out. He deletes CoolPeople.csv.

Next time the script runs, we get an exception:

With a blank $UpdatedCoolList variable it removes everyone’s access. Very not cool Kris.

Exceptions

Before we go into handling the sabotage, it is important to learn about exceptions. An exception is an error or unexpected result that PowerShell needs you to handle.

There are two types of exceptions: terminating and non-terminating. Terminating exceptions stop the running script. Non-terminating exceptions just write to the error pipeline.

Making a non-terminating exception a terminating exception is simple. You can set the command’s parameter to -ErrorAction to stop.

$UpdatedCoolList = Get-Content \\FileShare\Location\CoolPeople.csv -ErrorAction Stop

You can also set the default action of all errors to stop by setting the variable $ErrorActionPreference = "Stop".

In most cases, a cmdlet generates a non-terminating exception, but error handling with PowerShell requires a terminating exception to work.

Try/Catch/Finally

After the -ErrorAction is set to Stop, we can wrap it in a Try/Catch block. Try is where we run the command, and Catch is what will run if it runs into a terminating error.

Try {
    $UpdatedCoolList = Get-Content \\FileShare\Location\CoolPeople.csv -ErrorAction Stop
}
Catch {
    $_.Exception | Out-File C:\cool_log\krisdidit.log -Append
    Break
}

In this script-block, we captured the exception and put it in a log file. Break was used to exit the script so it would not continue. If we had left the catch block empty it would absorb the error and continue the script.

The last piece of the error handling with a Try/Catch/Finally block is the Finally. This is used to provide actions that will always run before exiting the script (or continuing on). This is mostly used for clean up. You can use it to close database connections, remove files, or close file locks.  Finally allows you to revert any changes done as a result of the script whether an exception is encountered or not.

Conclusion

That is it for the basics. Whenever you are dealing with elements that are volatile or out of your control, error handling is a great way to make sure that your script will not cause problems if things go wrong.

Ready to put the PowerShell scanner through its paces?

Take our 14-day Free Trial. Feel the power of the PowerShell scanner.
Start a Trial

Don't miss the next post!

May 2020 Patch Tuesday Vulnerabilities

May 2020 Patch Tuesday Updates and Vulnerabilities. This month has continued the trend of fewer issues that we have seen since February. CVE’s patched dropped from 113 all the way down to 111.