【问题标题】:Powershell: Why does System.Net.WebClient fail on the third openRead for the same hostPowershell:为什么 System.Net.WebClient 在同一主机的第三次 openRead 上失败
【发布时间】:2016-10-27 22:14:17
【问题描述】:

我创建了一个检查一堆 URL 的 Powershell 脚本。下面是使用 WebClient 从 url 列表中一一读取的代码 sn-p。

try {
    $log.debugFormat("Now checking endpoint={0}", $checkUrl)
    $wc.OpenRead($checkUrl)
    $log.infoFormat("guid={0} loop={1} endpoint={2} status=success", ($guid, $i, $checkUrl))
} catch [System.Net.WebException] {
    $log.errorFormat("guid={0} Could not connect to {1}", ($guid, $checkUrl))
    $ErrorMessage = $_.Exception.Message
    $log.errorFormat("{0}", $ErrorMessage)

奇怪的是,我提供的每台主机每三次尝试都会超时。首先,我花了几个小时对网络服务器配置进行故障排除,现在才意识到,当第三次尝试连接到同一主机时,是 Web 客户端本身以某种方式超时。

我已经尝试添加$wc.Dispose(),并且还尝试在循环中每次创建对象$wc = New-Object System.Net.WebClient,但没有帮助。

版本是Powershell -Command "Write-Host $psversiontable.psversion" 4.0,在 Windows 2012 上。

【问题讨论】:

    标签: powershell webclient powershell-4.0


    【解决方案1】:

    您需要关闭流,例如:

    $stream = $wc.OpenRead($checkUrl)
    $stream.Close()
    

    处置WebClient也是个好主意

    【讨论】:

    • Magic,在finally-block 中添加了$stream.close()$wc.dispose(),确实解决了问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    相关资源
    最近更新 更多