Search code examples
powershellhttp-status-codesinvoke-webrequest

Powershell webrequest handle response code and exit


I want it to exit when the response status code is 429, how can I do it? my looped ps1 script I don't want to use do or try or catch methods. Is there a simple method? this is my code and i want it to exit when response code 429

'header' = 'header'}
"@
$req = @{
    Uri         = 'https://mywebsite.com/api/'
    Headers     = $headers
    Method      = 'get'
    ContentType = 'application/json'}
while($true){
Invoke-WebRequest @req
status code 429 = exit}

Solution

  • Caveat: Given that your code makes ongoing requests in a tight loop, it should only be run against a test web service / site.

    I don't want to use do or try or catch methods.

    In Windows PowerShell, you must use try / catch:

    while (
     429 -ne 
     $(try { $null=Invoke-WebRequest @req } catch { $_.Exception.Response.StatusCode })
    ) { }
    

    In PowerShell (Core) 7+, you can use the -SkipHttpErrorCheck switch:

    while (429 -ne (Invoke-WebRequest -SkipHttpErrorCheck @req).StatusCode) { }
    

    See this answer for details.