How to test if I have a an active SpoService connection before starting a new 1

Welcome Forums General PowerShell Q&A How to test if I have a an active SpoService connection before starting a new 1

Viewing 2 reply threads
  • Author
    Posts
    • #278232
      Participant
      Topics: 5
      Replies: 3
      Points: 67
      Rank: Member

      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 🙂

    • #278352
      Participant
      Topics: 5
      Replies: 252
      Points: 999
      Helping Hand
      Rank: Major Contributor

      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.

      • This reply was modified 1 month, 1 week ago by Mike R..
      • #278472
        Participant
        Topics: 5
        Replies: 3
        Points: 67
        Rank: Member

        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

         

    • #278481
      Participant
      Topics: 17
      Replies: 1951
      Points: 3,987
      Helping Hand
      Rank: Community Hero

      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:

Viewing 2 reply threads
  • You must be logged in to reply to this topic.