首页 > 解决方案 > 当响应时间(不是名称解析)长于 x 时,有没有办法结束 Invoke-WebRequest?

问题描述

我想运行一个脚本来检查网站响应时间(不是 DNS 名称解析时间),当响应时间长于例如 60 秒时会引发异常。

我使用httpstat.us/200?sleep=70000(即等待 70 秒)进行测试,但找不到解决方案,因为-TimeoutSec只是检查名称解析时间。我不明白在这种情况下创建工作或计时器有何帮助。我在另一个论坛中尝试了以下代码,(当然)不起作用,因为它等待命令完成。如何在 60 秒后中断/中断它?

$url = 'httpstat.us/200?sleep=70000'
$Duration = 60

$TimeOut = New-TimeSpan -Seconds $Duration
$Sw = [Diagnostics.Stopwatch]::StartNew()
while ($Sw.Elapsed -lt $TimeOut) {
    try {
        Invoke-WebRequest -Uri $url
    } catch [System.Exception] {
        # Writing the exception in the console
        Write-Host $_.Exception
        exit;
    }
} #EndOf while ($Sw.Elapsed -lt $TimeOut)

标签: powershell

解决方案


如果在此示例中同时设置MaxServicePointIdleTime-TimeOutSec请求的参数在一秒钟后中止:

[System.Net.ServicePointManager]::MaxServicePointIdleTime = 1000

$url = 'httpstat.us/200?sleep=70000'
$Duration = 60

$TimeOut=New-TimeSpan -Seconds $Duration
$Sw=[Diagnostics.Stopwatch]::StartNew()
While ($Sw.Elapsed -lt $TimeOut)
{
    Try
    {
        Invoke-WebRequest -Uri $url -TimeoutSec 1
    }
    Catch [system.exception]
    {
        # Writing the exception in the console
        Write-Host $_.Exception
        Break
    }
} #EndOf While ($Sw.Elapsed -lt $TimeOut)

推荐阅读