Invoke-WebRequest设置超时

Jos*_*osh 18 powershell

我有一个长期运行的网页,我需要Powershell来打电话.我从任务管理器每晚运行它,具体如下:

powershell -Command "Invoke-WebRequest https://www.example.com/longrunningtask" 
Run Code Online (Sandbox Code Playgroud)

但PowerShell超时发生在网站响应之前.有没有办法将超时设置为Invoke-WebRequest超过标准的60秒?

Jef*_* E. 19

-TimeoutSec调用Invoke-WebRequestcmdlet 时,应该有一个参数可以提供整数值.

Invoke-WebRequest https://www.example.com/longrunningtask -TimeoutSec 60
Run Code Online (Sandbox Code Playgroud)

  • 我看到了,但这是DNS解析.立即找到DNS,但查询的时间比默认时间长.是否有可以更新的全局PS设置? (4认同)
  • 本身没有全局设置。大多数 Web cmdlet 的默认超时是从 [System.Net.HttpWebRequest.Timeout] 中读出的。您总是可以尝试制作 WebClient 类的稍微自定义的副本,然后更改 Timeout 属性。http://stackoverflow.com/questions/1789627/how-to-change-the-timeout-on-a-net-webclient-object 看看是否有效。 (2认同)

Mat*_*sen 6

您也许可以通过设置静态ServicePointManager.MaxServicePointIdleTime属性来解决超时问题。默认值为 100000ms(100 秒):

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

# Now run your Invoke-WebRequest after making the change
Run Code Online (Sandbox Code Playgroud)

更改ServicePointManager仅适用于当前应用程序域,并且不会在会话之外持续存在(即,您需要在每次运行脚本时执行此操作)


Til*_*ilo 0

PS 7.4 有这个: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest ?view=powershell-7.4

Invoke-WebRequest -Uri "https://google.com:9811" -ConnectionTimeoutSeconds 2

Measure-Command { Invoke-WebRequest -Uri "https://google.com:99" }
Measure-Command { Invoke-WebRequest -Uri "https://google.com:99" -ConnectionTimeoutSeconds 2 }

##timeout in PS 7.4
-ConnectionTimeoutSeconds
-OperationTimeoutSeconds
Run Code Online (Sandbox Code Playgroud)