You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本调用Invoke-RestMethod未使用hosts文件更新的IP地址

解决PowerShell修改hosts后Invoke-RestMethod复用旧IP的DNS缓存问题

问题核心是**.NET框架的ServicePointManager会独立缓存DNS解析结果**,即使修改了hosts文件或刷新系统DNS缓存,默认情况下它依然会复用之前的解析结果,直到缓存超时。以下是几种针对性解决方法:

方法一:强制.NET即时刷新DNS缓存

修改脚本,在更新hosts后添加两步操作:禁用DNS缓存超时、关闭对应域名的现有连接点,强制下次请求重新解析IP。

修改后的代码示例:

# Define an array of IP addresses
$ipAddresses = @(
    "1.2.3.4", 
    "5.6.7.8", 
    "5.6.3.3"
)

foreach ($ipAddress in $ipAddresses) {
    add-host $hostsFilePath  $ipAddress $domainName
    
    $headers = @{
        "Authorization" = "Bearer ******"
        "content-type" = "application/json; charset=utf-8"
    }

    $requestCount = 10
    
    # 禁用.NET DNS缓存超时,强制每次请求重新解析
    [System.Net.ServicePointManager]::DnsRefreshTimeout = 0
    # 关闭对应域名的现有连接点,清除缓存
    $servicePoint = [System.Net.ServicePointManager]::FindServicePoint($subsequentEndpoint)
    $servicePoint.Close()

    for ($i = 1; $i -le $requestCount; $i++) {
        $subsequentResponse = Invoke-RestMethod -Uri $subsequentEndpoint -Method Post -Headers $headers -Body $body
    }

    remove-host $hostsFilePath  $ipAddress $domainName
}

方法二:结合系统DNS缓存刷新

在修改hosts后,同步刷新系统DNS缓存,确保系统层面的解析也更新(需管理员权限执行):
在add-host执行后添加:

# 刷新系统DNS缓存
ipconfig /flushdns | Out-Null

方法三:绕开DNS解析(直接用IP构造请求)

如果业务允许,可以直接用目标IP构造请求Uri,彻底绕过DNS缓存问题:

# 从原Endpoint中提取路径部分
$uriBuilder = [System.UriBuilder]$subsequentEndpoint
$path = $uriBuilder.Path
# 用当前迭代的IP拼接新请求地址(注意协议是http/https)
$newUri = "https://$ipAddress$path"

# 后续请求使用构造好的新Uri
$subsequentResponse = Invoke-RestMethod -Uri $newUri -Method Post -Headers $headers -Body $body

关键说明

  • ServicePointManager的DNS缓存是.NET应用级别的,和系统DNS缓存相互独立,仅刷新系统缓存无法解决问题。
  • 设置DnsRefreshTimeout = 0会让.NET每次请求都重新解析DNS,适合测试场景,生产环境可根据需求调整超时值。
  • Close()方法会关闭现有连接,确保下次请求建立新连接时重新解析IP地址。

内容的提问来源于stack exchange,提问作者RoG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:38:08