Hi,
I’m writing a bit of code that tests if an existing SpoService exists by watching for failure of a Get-SpoSite:
try
{
$SPOSessions = Get-SpoSite $OneDriveAdminURL | Select-Object -Property Url
$SPOSessionExists = (@($SPOSessions) -like “@{Url=$($OneDriveAdminURL)”).Count -gt 0
$SPOSessionExists = (Get-PnpConnection | Where-Object Url -eq $OneDriveAdminURL | Select-Object -Property Url | Measure-Object).Count -gt 0
}
catch
{
$SPOSessionExists = $false
}
It works, but I always get an error in the error stack:
Exception Details:
Message : No connection available. Use Connect-SPOService before running this CmdLet.
I thought putting in in a try/catch would avoid the error? Anyone know how I could test without generating an error?
Thanks
By default the catch statement will only handle terminating errors. This is not a terminating error. To properly handle this exception either make the command causing the error create terminating errors only with the common parameter/value of -ErrorAction Stop. In you post I don’t see the full error message so I’m not sure which command is causing it.
Thanks Mike R.
I did this and it worked:
try
{
$SPOSessionExists = (Get-SPOSite | Measure-Object).Count -gt 0
}
catch [System.InvalidOperationException]
{
$SPOSessionExists = $false
$Error.Remove($error[$Error.Count - 1]) # removes the error that has been trapped so the script can close cleanly
}
catch
{
$SPOSessionExists = $false
}
Thanks,
Michael
The cmdlet throws an error that explains that you need to use Connect-SPOSite again. The only reason you would catch that specific exception is if you put code in there to do something like, Connect-SPOSite. Using the try\catch you can add some details to the error message if you want, otherwise, you are just setting a flag for any error in both cases. Try something like this:
$site = 'https://contoso.sharepoint.com'
try {
$spoSite = Get-SPOSite -Identity $site -ErrorAction Stop
}
catch {
$msg = 'Error connecting to Share Point site {0}. {1}' -f $site, $_
Throw $msg
}
if ($spoSite) {
#Do stuff
}