我有一个长时间运行的网页,我需要使用PowerShell进行调用。我每天晚上都从任务管理器运行它,并使用以下命令:
powershell -Command "Invoke-WebRequest https://www.example.com/longrunningtask"
但在网站响应之前,PowerShell 超时了。有没有办法将 Invoke-WebRequest
的超时时间设置得比标准的 60 秒更长?
我有一个长时间运行的网页,我需要使用PowerShell进行调用。我每天晚上都从任务管理器运行它,并使用以下命令:
powershell -Command "Invoke-WebRequest https://www.example.com/longrunningtask"
但在网站响应之前,PowerShell 超时了。有没有办法将 Invoke-WebRequest
的超时时间设置得比标准的 60 秒更长?
在调用Invoke-WebRequest
命令时,您可以输入一个整数值到-TimeoutSec
参数中。
Invoke-WebRequest https://www.example.com/longrunningtask -TimeoutSec 60
您可以通过设置静态的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进行网络请求的命令,其中包含“&”:
powershell -Command "Invoke-WebRequest ""http://localhost/index.php?option=val1""&""view=val2""&""key=val3""&""profile=2""" -TimeoutSec 600
请注意添加了双引号,希望对需要从命令行执行网络请求的人有所帮助:)
我知道这不完全是你需要的,因为使用这种方法基本上是为整个调用设置了一个超时:
但是,如果您只需要设置大致超时时间,考虑到在大多数常见情况下,大部分时间都花费在第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