Skip to content

Try, catch, finally Statements

The try block is used to define a section of a script for executing your code script. Within this block, you’ll want everything that you want monitored for errors. This should not be handled within your finally statement, and never in your catch.

Due to the nature of Try, you are required to use a catch or finally block alongside the statement. Without a catch or finally, it’d be no different that running a script without it at all.

Terminal window
try.ps1
try {
Write-host "Go Crazy here."
if ($Alive){
write-output "Start building up statements"
$Var52 = "And doing what you need to"
}
Else{
Write-output "Because your logic should be handled within the try."
}
}
Catch {...}

The catch block is for handling terminating exceptions thrown within the try block. When the error is thrown, the try block terminates, heads into catch, before proceeding to finally.

For example, if System.UnauthorizedAccessException is thrown during try, it heads to the catch block. This errors informs us that that the shell or script is not running as administrator, or the user does not have sufficient permissions.

You can define multiple catches. Use the FullyQualifiedErrorId within [ ] to define what to catch, or leave it undefined to catch all thrown, terminating errors.

catch.ps1
try{...}
catch [System.UnauthorizedAccessException] {
Write-output "Please run the script as Administrator."
}
catch {
Write-output "Unhandled exception $_"
}

Finally runs, regardless of how your try/catch configuration goes. Finally should be used for clean up or post try validation, or stopping logging/transcripts. No further actions should be kept here. If child processes were spawned, this is a good place to kill them off. Here is a full example of how the syntax should now look using try, catch, finally.

finally.ps1
try {
<#Do this till throwing or finishing#>
}
catch {
<#Do this if a terminating exception happens#>
}
finally {
<#Do this after the try block regardless of whether an exception occurred or not#>
}

.ps1
# We define -Erroraction Stop a few times in this script so non-terminating errors are now caught.
$exit = 0
try {
$featurename = "SMB1Protocol"
$featuresetup = {
(Get-WindowsOptionalFeature -Online -FeatureName "$featurename" -ErrorAction Stop).State
}
$feature = New-Object PSObject
Add-Member -InputObject $feature -MemberType ScriptProperty -Name State -Value $featuresetup
switch ($($Feature.state)) {
"Enabled" {
Write-Output "$featurename is $($feature.state)"
}
"Disabled" {
Write-Output "$featurename is $($feature.state), attempting to Enable"
$Result = Enable-WindowsOptionalFeature -Online -FeatureName "$featurename" -All -NoRestart -ErrorAction Stop
}
}
}
catch {
Write-Output "$_"
$exit = 1
}
finally {
write-output "Final state is $($feature.state)."
exit $exit
}

About_Try_Catch_Finally Everything you wanted to know about exceptions