I need to produce some output when Invoke-WebRequest exceeds the time limit set by the -TimeoutSec parameter. How can I build an If condition that runs when this is the case?
In other words; what goes in place of ????? in the example below?:
Try {
Invoke-RestMethod -Uri $Uri -contentType "application/json"
-Method Post -Headers $Headers -Body $Body -TimeoutSec 8
}
Catch {
If (?????) {
Write-Host "the request timed out..."
}
}
In Windows PowerShell, the exception thrown will be a [System.Net.WebException]
with the Status
field set to 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
}