调用 Invoke-WebRequest 设置超时时间

30

我有一个长时间运行的网页,我需要使用PowerShell进行调用。我每天晚上都从任务管理器运行它,并使用以下命令:

powershell -Command "Invoke-WebRequest https://www.example.com/longrunningtask" 

但在网站响应之前,PowerShell 超时了。有没有办法将 Invoke-WebRequest 的超时时间设置得比标准的 60 秒更长?


你计算/测量过超时所需的时间吗?是60秒吗?100秒吗? - Mathias R. Jessen
@MathiasR.Jessen 100 秒 - Josh
那我建议你看看我的答案 :) - Mathias R. Jessen
4个回答

34

在调用Invoke-WebRequest命令时,您可以输入一个整数值到-TimeoutSec参数中。

Invoke-WebRequest https://www.example.com/longrunningtask -TimeoutSec 60

6
我看到了,但那是关于DNS解析的。DNS可以立即找到,但查询所需时间比默认时间长。是否有一个全局的PS设置可以更新? - Josh
3
并没有全局设置。大多数Web cmdlet的默认超时时间都是从[System.Net.HttpWebRequest.Timeout]中读取的。您可以尝试制作一个稍微定制的WebClient类的副本,并更改Timeout属性,以查看是否有效。 请参阅https://dev59.com/lHI-5IYBdhLWcg3wkJMA。 - Jeffrey Eldredge

6

您可以通过设置静态的ServicePointManager.MaxServicePointIdleTime属性来避免超时问题。默认值为100000毫秒(100秒):

# Bump it up to 180 seconds (3 minutes)
[System.Net.ServicePointManager]::MaxServicePointIdleTime = 180000

# Now run your Invoke-WebRequest after making the change

ServicePointManager的更改仅适用于当前应用程序域,并且不会在会话结束后保留(即每次运行脚本时都需要进行更改)


我将语句更改为powershell -command "[System.Net.ServicePointManager] :: MaxServicePointIdleTime = 600000; invoke-webrequest http://www.example.com/longrunningtask",但它仍然在100秒时终止。 - Josh
没有成功,不过 Jeffrey 的答案很好用。 - hanjo

1

这里是我成功尝试使用PowerShell进行网络请求的命令,其中包含“&”:

powershell -Command "Invoke-WebRequest ""http://localhost/index.php?option=val1""&""view=val2""&""key=val3""&""profile=2""" -TimeoutSec 600

请注意添加了双引号,希望对需要从命令行执行网络请求的人有所帮助:)


0

我知道这不完全是你需要的,因为使用这种方法基本上是为整个调用设置了一个超时:

  1. 构建客户端内容
  2. 在DNS上解析地址
  3. 如果使用安全连接,则最终进行握手
  4. 发送请求
  5. 等待响应
  6. 构建所有包装响应的对象

但是,如果您只需要设置大致超时时间,考虑到在大多数常见情况下,大部分时间都花费在第4和第5点上,使用 Start-Job + Wait-Job -Timeout + Receive-Job 应该可以完成工作:

$job = Start-Job -ScriptBolck { Invoke-WebRequest "https://www.example.com/longrunningtask"}
# Wait for the termination of the job, or 60s, whichever occurs first
Wait-Job -Timeout 60
$response = Receive-Job $job

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接