英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论