PowerShell:如何确定Invoke-WebRequest是否超时?

问题描述

当Invoke-WebRequest超过-TimeoutSec参数设置的时间限制时,我需要产生一些输出在这种情况下,如何建立一个If条件运行?

换句话说;代替??????在下面的示例中?:

Try {
  Invoke-RestMethod -Uri $Uri -contentType "application/json"
   -Method Post -Headers $Headers -Body $Body -TimeoutSec 8
}
Catch {
 If (?????) {
    Write-Host "the request timed out..."
  }
}

解决方法

在Windows PowerShell中,引发的异常将是[System.Net.WebException],且Status字段设置为Timeout

try{
  Invoke-WebRequest 'http://hostname.fqdn/really/slow/endpoint/' -TimeoutSec 3 -UseBasicParsing
}
catch [System.Net.WebException] {
  if($_.Exception.Status -eq 'Timeout'){
    # the request timed out
  }
  # something else went wrong during the web request
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...