SharePoint Online: Error Handling with Try Catch in PowerShell


One of the best practices while writing PowerShell scripting is handling potential errors to ensure 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. So, 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.

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

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 error was not handled by the catch block! 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.

Using "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

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 error? 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 -UseWebLogin

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 was an error or not. In this way, we can perform actions that need to be made regardless 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 subsequent script. It suppresses the error from outputing into the shell.
  • Continue - (Default) Display an error message and attempt to continue execution of subsequence commands.
  • Inquire - Prompts the user whether to continue or terminate the action
  • Stop - Terminate the action with error.
  • Break - Enter the debugger when an error occurs or when 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 saved preference. Ignore isn't a valid value for the $ErrorActionPreference variable.

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.