Powershell Script does not wait for the response from Invoke-RestMethod cmdlet

Viewed 5237

I am new to powershell. I have a powershell script which basically makes an REST API request and gets back a JSON response. But I have an issue with the Invoke-RestMethod cmdlet. I mean the script sometimes doesn't wait for the response and continues with the next line of code.

Is there some trick in powershell which asks the code to wait for the API response and then run the remaining code. Below is my code

if ($EventID -eq '4726') { 
    $ad_user = "$TargetUsername@avayaaws.int" 

    $jsonbody = @{

                   "setupName" = "avayadev-or"
                   "instanceName" = "000_JumpServer_DMZ"
                   "command" = "$Command"
                    "parameters" = @{
                                     "mobile" = "$getMobileAttr"
                                     "ad_user"="$ad_user"
                                     "label" ="$environment"
                                    }
                   "eventToken" = "optional"

                  } | ConvertTo-Json

    #$response = Start-Job {
    #    Invoke-RestMethod -Uri $uri -Method $verb -Body $jsonbody -Headers $header 
    #} | wait-job | receive-job 
    #$response = Invoke-RestMethod -Uri $uri -Method $verb -Body $jsonbody -Headers $header
    $response = Invoke-WebRequest -Uri $uri -Method $verb -Body $jsonbody -Headers $header
    $EventTrigger = $translEvent4726
    Write-Output "Response is: $response"
    PushLogs -transaction $EventTrigger -adUser $ad_user -transResult $response

}

I have tried many ways like using Out-Null and Wait-Job, Recieve-Job but couldn't get it to work. Any help is much appreciated.

0 Answers
Related