locked
Run Invoke-Restmethod in foreach loop - Error Underlying connection RRS feed

  • Question

  • I am running Invoke-Restmethod multiple times in a loop

    Foreach ( //)

    {

    Invoke-RestMethod -UseDefaultCredential -Method Get -url //  

    //work around

    start-sleep 5

    }

    First time it runs the invoke-restmethod, it works fine but after that I get

    Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive.

    My current workaround is to put a start-sleep for 3~5 seconds at the end of the loop. 

    what could I do to avoid the underlying connection error?

    Tuesday, May 15, 2018 9:37 PM

All replies

  • Don't reconnect each time.  Use the web session variable "SessionVariable" in subsequent connections.


    \_(ツ)_/

    Tuesday, May 15, 2018 9:46 PM
  • Thank you for your suggestion,

    I tried

    $branches = (Invoke-RestMethod -UseDefaultCredentials -Method Get -uri $teamProjectUrl -SessionVariable mySession)

    //condition

    foreach ()

    {

    $branches = (Invoke-RestMethod -UseDefaultCredentials -Method Get -uri $teamProjectUrl -WebSession $mySession)

    }

    but I still get "Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive." after it runs through the loop couple times.

    Tuesday, May 15, 2018 10:51 PM
  • That is an issue between you and the web service.

    Perhaps you need to check your SSL settings.

    Try adding this at the beginning.

    [Net.ServicePointManager]::SecurityProtocol+='tls12'


    \_(ツ)_/

    Tuesday, May 15, 2018 11:10 PM
  • I added and now I have the following.

    PS P:\> [Net.ServicePointManager]::SecurityProtocol
    Ssl3, Tls, Tls12

    Still facing the error message

    Tuesday, May 15, 2018 11:23 PM
  • Check with the owner of the service.


    \_(ツ)_/

    Tuesday, May 15, 2018 11:25 PM
  • Also you syntax is wrong and you do not reuse credentials when using a websession.

    $branches = Invoke-RestMethod -UseDefaultCredentials -Method Get -uri $teamProjectUrl -SessionVariable mySession
    where(1){
        $branches = Invoke-RestMethod -Method Get -uri $teamProjectUrl -WebSession $mySession
    }
    


    \_(ツ)_/

    Tuesday, May 15, 2018 11:48 PM