'need Invoke-WebRequest to finish before making another Invoke-WebRequest

I have some Powershell code where I make a request for a bearer token, then use the response to make another request to an API. What's happening is the request to the API is executing before the token request can finish.

How can I make sure the token request finishes before the API request starts?

I've tried adding various solutions to my token request code and none work. I've tried adding | Wait-Process and | Out-Null. I've also tried putting the token request in a try/catch block.

Here's my code:

Write-Host "Request new bearer token"
$form = @{
    grant_type = 'client_credentials'
    client_id = '........'
    client_secret = '........'
    resource = 'https://management.azure.com'
}

$tokenreq = Invoke-WebRequest -Uri https://login.microsoftonline.com/08c93a8c-......./oauth2/token -Method Post -Form $form

$token = $tokenreq.access_token

#this webrequest runs with $token not being set
Invoke-WebRequest -Uri https://management.azure.com/subscriptions/{subscription id}/providers/Microsoft.CostManagement/query?api-version=2021-10-01 -Method Post -Authentication Bearer -Token $token -Body $body -ContentType 'application/json'

I'm looking for something similar to a promise or a callback function like in Javascript.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source