1
$uri="http:\\www.SomeUrl.com"
Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing}

In above powershell script, how can I exit from Invoke-WebRequest if it takes time more than 10 secs, and return a error code if possible.

Jawad
  • 11,028
  • 3
  • 24
  • 37
Amith B
  • 327
  • 2
  • 11
  • For cmdlets that do not have already a `-Timeout` parameter, see: [Powershell command timeout](https://stackoverflow.com/questions/19855822/powershell-command-timeout) – iRon Feb 17 '20 at 12:42
  • In general, you can set a timeout on jobs: https://stackoverflow.com/questions/21176487/adding-a-timeout-to-batch-powershell – js2010 Feb 17 '20 at 17:23

1 Answers1

1

You can use the Timeout parameter to the Invoke-WebRequest command,

$uri="http://www.SomeUrl.com"
Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing -Timeout 10}

You can cover it with try / catch block to get the error message.

try {
    $uri="http://www.SomeUrl.com"
    Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing -Timeout 10 -ErrorAction Stop}
}
catch {
    Write-Output "Timeout occured. Exception: $_"
}

You can also use -Headers @{"Cache-Control"="no-cache"} with Invoke-WebRequest which will not cache the pages you are visiting.

Jawad
  • 11,028
  • 3
  • 24
  • 37
  • try { $uri="http:\\www.google.com" $time=Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing -Timeout 1 -ErrorAction Stop} Write-Host "Total Seconds: "$time.TotalSeconds } catch { Write-Output "Timeout occured. Exception: $_" } Hi, I tried the above thing, but the result I got is as below output: Total Seconds: 4.1600271 – Amith B Feb 17 '20 at 06:33
  • Since it has exceeded 1 second, it should through error right. – Amith B Feb 17 '20 at 06:35
  • When you make a call, multiple times, the data Is already cached. Try that with another site that might take longer to download – Jawad Feb 17 '20 at 06:38
  • Thank you so much , it worked with different url. But , is there any way to clear the cache and continue with same url. – Amith B Feb 17 '20 at 06:46
  • `-Headers @{"Cache-Control"="no-cache"}` ... you can add this to your Invoke-WebRequest – Jawad Feb 17 '20 at 06:56