Powershell webrequest处理响应代码并退出

huangapple go评论48阅读模式
英文:

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}
英文:

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}

答案1

得分: 0

注意: 由于您的代码在紧密循环中进行持续请求,应仅对 测试 Web 服务/站点运行它。

Windows PowerShell 中,您**_必须_使用 try / catch**:

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

PowerShell (Core) 7+ 中,您可以使用 -SkipHttpErrorCheck 开关:

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

有关详细信息,请参阅此答案

英文:

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.

huangapple
  • 本文由 发表于 2023年3月4日 00:28:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定