63’s blog

都内のSEのブログです(*‘ω‘ *)技術は好きですが仕事は嫌いです。

Invoke-RestMethod -Uri を繰り返したいとき

PowerShellAPIをリクエストしたいときとか、
何度もリクエストをトライしてほしい時ってありますよね。


普通だったらレスポンスコードを条件に
ループを繰り返してリトライしてあげたらいいだけです。

※ここから本題です。
このコードで$resにResponse情報が入ると思ったのですが、、、、、空文字でした。(*‘∀‘)?

$res = Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $bodyBytes

じゃあ、Response情報はどこにいくのか下記が答えです。

try{
    Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $bodyBytes
}
catch{
    Write-Host "StatusCode:"+ $_.Exception.Response.StatusCode.value__
    Write-Host "StatusDescription:"+ $_.Exception.Response.StatusDescription
}

catchの中の$_.Exception.ResponseがResponse情報を持っている結果でした。
なので、リクエストが成功するまで繰り返しを行う処理は以下のように記載します。

    $retryCnt=1
    while ($retryCnt -le $retryTimes) {
        try{
            $res = Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $bodyBytes
            return
        }
        catch{
            Write-Host "StatusCode:"+ $_.Exception.Response.StatusCode.value__
            Write-Host "StatusDescription:"+ $_.Exception.Response.StatusDescription
                        
            $retryCnt+=1
        }
    }