SharePoint Online: Error Handling with Try Catch in PowerShell

One of the best practices while writing PowerShell scripting is handling potential errors to ensure the smooth execution of the script when something goes wrong. Who can guarantee a script can run correctly in different environments every time? Error handling in PowerShell is made easy with try-catch blocks similar to .NET framework. When something goes wrong in the script inside the “Try” block, the flow of the script is transferred to the “Catch” block to handle the error. Let’s see how to use the try-catch in PowerShell scripts for SharePoint Online.

Try Catch in PowerShell SharePoint Online

Here is a basic example of how Try-Catch error handling works in PowerShell for SharePoint Online:

Try {
    Connect-SPOService -url "https://crescent-admin.sharepoint.com"
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}
Try Catch PowerShell SharePoint Online

In this example, if an exception is thrown while executing the code in the try block, the script will jump to the catch block, where the error message will be displayed using the Write-Host cmdlet. Similarly, Here is how you can use Try-Catch in CSOM scripts to check if a list exists:

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
 
#Function to check if a list or document library exists
Function Check-SPOListExists([Microsoft.SharePoint.Client.ClientContext]$Ctx, [String]$ListName)
{
    Try {
        $List = $Ctx.Web.Lists.GetByTitle($ListName)
        $Ctx.Load($List)
        $Ctx.ExecuteQuery()
        Return $True
    }
    Catch [Exception] {
        Write-host $_.Exception.Message -f Red
        Return $False
     }
}
    
#Config Parameters
$SiteUrl = "https://crescent.sharepoint.com/sites/projects"
$ListName="Project Documents"
 
#Get Credentials to connect
$Cred= Get-Credential
   
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
    
#Call the function to Check List Exists
Check-SPOListExists -Ctx $Ctx -ListName $ListName

You can do anything you want with the error message, like displaying a customized warning on the screen instead of an error! However, not all exceptions can be handled by the Try-Catch block! Let’s run the following script:

$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$SubSiteURL = "2010"
  
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

Try { 
    #Get a subsite
    $Web = Get-PnPWeb -Identity $SubSiteURL
}
Catch {
    Write-host "Error:"$_.Exception.Message -f Red
}

If you run this script, You’ll get:

sharepoint online powershell try catch

Although we’ve used the Try-Catch block in the script, you can find the catch block did not handle the error! This is because: There are two types of errors in PowerShell.

  1. Terminating error 
  2. Non-terminating error.

A terminating error is an error that will halt a function or operation. Non-terminating errors allow PowerShell to continue and usually come from cmdlets or other managed situations. By default, the Try-Catch block will be able to catch only terminating errors! To be able to catch Non-Terminating errors, you should set either set the $ErrorActionPreference variable or set the ErrorAction parameter of the cmdlet.

Try with Multiple Catch Blocks

try {
	 //Some Script
}
catch [Exception 1],[Exception 2] {
    //Action something
}
catch {
    //Generic error
    Write-host $_.Exception.Message
}

Using the “ErrorAction” Parameter:

Every PowerShell cmdlet supports the ErrorAction switch. By specifying “-ErrorAction Stop” at the end of a cmdlet, you ensure any errors it throws are treated as terminating and can be caught by the catch block. 

Try { 
    #Get a subsite
    $Web = Get-PnPWeb -Identity $SubSiteURL -ErrorAction Stop
}
Catch {
    Write-host "Subsite doesn't Exist!" -f Red
}
sharepoint online try catch errorAction Stop

Here is another example:

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Retail"
$FileURL = "/sites/Retail/Shared Documents/2019/SiteAdmins-UNKNOWN.csv"

Try {
    #Connect to SharePoint admin site
    Connect-PnPOnline -Url $SiteURL -Interactive

    #Get the File
    $File = Get-PnPFile -Url $FileURL -AsFileObject -ErrorAction Stop
    Write-host $File.Length
}
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Using the $ErrorActionPreference variable

It is also possible to treat all errors as terminating using the ErrorActionPreference variable. How do you catch a non-terminating mistake? Basically, you tell PowerShell to treat it as terminating. You can turn all your errors to the terminating by setting – $ErrorActionPreference = “Stop”, And later resetting it back to “Continue”. Here is an example:

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$SubSiteURL = "2010"
  
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

Try {
    #Set Error Preference variable to Stop
    $ErrorActionPreference = "Stop" 
    #Get a subsite
    $Web = Get-PnPWeb -Identity $SubSiteURL
}
Catch {
    Write-host "Subsite doesn't Exist!" -f Red
}
Finally {
    #Rest Error Preference to Default
    $ErrorActionPreference = "Continue"
}

The “Finally” block runs every time, regardless of whether there is an error. In this way, we can perform actions that must be made irrespective of whether an operation succeeds or fails.

The $ErrorActionPreference variable specifies the action to take in response to an error occurring. The following values are supported:

  • SilentlyContinue – Don’t display an error message continue to execute the subsequent script. It suppresses the error from outputting into the shell.
  • Continue – (Default) Display an error message and attempt to continue the execution of subsequence commands.
  • Inquire – Prompts the user on whether to continue or terminate the action
  • Stop – Terminate the action with an error.
  • Break – Enter the debugger when an error occurs, or an exception is raised.
  • Ignore: Suppresses the error message and continues to execute the command. The Ignore value is intended for per-command use, not for use as a saved preference. Ignore isn’t a valid value for the $ErrorActionPreference variable.

For more information on PowerShell Error Handling, refer to: Error Handling with PowerShell Try Catch Block: Demystified!

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *