powershell - 当响应时间(不是名称解析)长于 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)
解决方案
如果在此示例中同时设置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)
推荐阅读
- html - 如何在不改变主体的情况下改变 div 元素的方向
- javascript - 第一次调用 Setinterval() 后滚动到 div 的底部
- laravel - 有没有办法在 Laravel 5.8 中测试 Eloquent Observers?
- sql - ORACLE SQL 触发器:PLS-00103:在预期以下情况之一时遇到符号“(”:
- c - 使用 GCC 为原始汇编代码注入编译代码
- python - 困难物体的OpenCV物体检测
- apache-kafka - 删除 Apache kafka 中的主题消息
- javascript - Sending FormData from modal to parent component's method in react
- haskell - 坚持极小极大算法——下一步是什么?哈斯克尔
- r - 将每组的多行合并为一个,同时仅合并R中的一些列数据