PowerShell中Invoke-WebRequest的重试参数为何未生效?
问题原因分析
- PowerShell 7.x 里
Invoke-WebRequest的内置重试参数(MaximumRetryCount和RetryIntervalSec)只针对特定错误触发重试,并非所有网络异常都会触发。 - “No such host is known” 属于 DNS 解析失败的底层错误,对应
HttpRequestException或其内部嵌套的Win32Exception,这类错误不在内置重试的触发范围内。 - 内置重试默认仅覆盖:HTTP 5xx 系列状态码、连接超时、连接重置这类已建立连接后出现的错误;DNS 解析失败属于连初始连接都无法建立的前置错误,因此不会触发内置重试逻辑。
解决思路
如果需要对 DNS 解析失败这类错误执行重试,不能依赖内置参数,得手动实现循环重试逻辑,示例代码如下:
$maxRetry = 10 $retryWaitSec = 10 $targetUrl = "你的目标Web服务URL" for ($attempt = 1; $attempt -le $maxRetry + 1; $attempt++) { try { $response = Invoke-WebRequest -Uri $targetUrl -ContentType "application/xml" # 处理返回的XML数据 break # 请求成功,跳出重试循环 } catch { $errorMsg = $_.Exception.Message if ($errorMsg -match "No such host is known" -or ($_.Exception.InnerException -and $_.Exception.InnerException.Message -match "No such host is known")) { if ($attempt -eq $maxRetry + 1) { throw "已重试$maxRetry次,仍无法解析主机:$errorMsg" } Write-Warning "第$attempt次请求失败:$errorMsg,将在$retryWaitSec秒后重试" Start-Sleep -Seconds $retryWaitSec } else { # 非DNS错误直接抛出 throw $_ } } }
内容的提问来源于stack exchange,提问作者beta
相关产品推荐
相关产品推荐

