I'm frequently tasked with automating various tasks in our M365 tenant, usually by writing scripts that generate report.csv and log.csv files. I append any errors to log.csv. However, I'm encountering issues with try-catch blocks not functioning as expected. For instance, when I attempt to retrieve the licenses assigned to a user with `Get-MsolUser -UserPrincipalName $user | Select-Object -ExpandProperty Licenses`, the catch block doesn't trigger for users who no longer exist in our tenant. After some investigation, I found that I could save the command's output to a variable to check if the user exists, and this workaround has worked for some commands. Yet, I'm facing a similar issue with the command `$userOD = Set-SPOSite "https://mytenant-my.sharepoint.com/personal/$($user)_tenant_edu" -LockState ReadOnly`, which also doesn't cause the catch block to execute even when users don't exist; it merely logs an error to the console, returning $true instead. I'm puzzled whether I'm misunderstanding how try-catch functions in PowerShell or if there are nuances with certain commands. Any insights would be greatly appreciated!
3 Answers
Try-catch in PowerShell only catches terminating errors, which are errors that stop the script completely. If you're dealing with non-terminating errors (like 'not found'), you need to configure the `$ErrorActionPreference` to `Stop` or use `-ErrorAction Stop` in your command. It's a common pitfall! Just a heads up, the MSOL API is phasing out, so it might be time to look for alternatives depending on your future needs.
Just so you know, MSOL is officially deprecated as of April 1st. You might want to consider updating your scripts to use alternatives before they stop working entirely.
You're correct that try-catch handles terminating errors. To achieve the behavior you want, add the `-ErrorAction Stop` parameter to your commands. For instance: `Get-MsolUser -UserPrincipalName $user -ErrorAction Stop | Select-Object -ExpandProperty Licenses`. This should allow the catch block to work as you'd expect.
Related Questions
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String