0

I have written a couple of try & Catch blocks when trying to access properties from Azure however the catch doesnt seem to handle the errors.

I was wondering is there anything that needs doing for the Az & MS.graph modules to catch errors? Two examples below work when the correct params are passed however if the wrong params are passed you will get an error which doesnt run the catch code.

$session = Get-AzWvdUserSession -HostPoolName $hostpoolname -ResourceGroupName $AvdRGName | Select-Object * | Where-Object { $_.ActiveDirectoryUserName -eq "domain\$username" } -ErrorAction Stop
if ($session.id -ne $null) {
    Write-Host "User is logged into AVD session, please log off user & re-run pipeline"
    Write-Host ***********************************
    Write-Host "Session detail:" $session.Id
    Write-Host ***********************************
    exit
} } catch {
$message = $_.Exception.message
Write-Host "Error checking user session in AVD Hostpool" $message }

try {
Write-Host ***********************************
Write-Host "Connecting to MS Graph API......"
Connect-MgGraph -Scopes 'User.Read.All', 'Directory.Read.All'

$userAttributes = Get-MgUser -UserId $username@iamdavidson.co.uk | Select-Object *
$fileShareName = $userAttributes.OnPremisesSecurityIdentifier + "_" + $userAttributes.OnPremisesSamAccountName
Write-Host ***********************************
Write-Host "The folder name for the users FSLogix profile is:" $fileShareName
Write-Host *********************************** } catch {
Write-Host "Error checking getting user properties using MS Graph" }
Mr I
  • 23
  • 6
  • 1
    In short: `try` / `catch` only acts on _terminating_ errors, whereas it is far more typical for cmdlets to report _non-terminating_ errors. For the `catch` block to get invoked, non-terminating errors must be promoted to terminating ones by passing `-ErrorAction Stop` or by setting `$ErrorActionPreference = 'Stop'` beforehand. See the linked duplicate for more information. – mklement0 Nov 11 '22 at 14:47

0 Answers0