首页 > 解决方案 > PowerShell 调用-RestMethod 超时

问题描述

如果通过 PowerShell 命令可用,我会检查一些服务(回旋处 15)。如果服务可用,则脚本运行时间很好,但如果某些服务不可用,则脚本运行时间不好!那么如何确定Invoke-RestMethod请求/响应的特定时间呢?我知道有一个 Parameter -TimeoutSec。例如,如果我在请求超时 4 秒后没有得到响应并抛出错误!

Invoke-RestMethod $uri -TimeoutSec

也许我误解了 Parameter -TimeoutSec

标签: powershell

解决方案


根据帮助:

> get-help Invoke-RestMethod -Parameter Timeoutsec

-TimeoutSec <Int32>
    Specifies how long the request can be pending before it times out. Enter a value in seconds. The default value, 0, specifies an indefinite time-out.

所以参数需要一个整数来表示超时应该多长时间。

Invoke-RestMethod $uri -TimeoutSec 4

请注意帮助中的警告:

A Domain Name System (DNS) query can take up to 15 seconds to return or time out. If your request contains a host name that requires resolution, and you set TimeoutSec to a value greater than zero, but less than 15 seconds, it can take 15 
seconds or more before a WebException is thrown, and your request times out.

推荐阅读