Search code examples
powershellconnection-timeoutinvoke-webrequest

PowerShell, how to handle a page timeout from an Invoke-WebRequest?


I found that a site that I wanted to parse was down today when I went there to download a file.

The code I ran is:

$url = "https://notepad-plus-plus.org/downloads"
$page = Invoke-WebRequest -uri $url -UseBasicParsing

How can I intercept and handle this?

  • Is there a way to gracefully time out my request after 2 seconds if it does not get a response (which could be from the site being down or from my own internet having problems)?
  • What might be the best way to detect if what was returned is "connection timeout junk" as opposed to useful data that I can work with?

output from Invoke-WebRequest

$url = "https://notepad-plus-plus.org/downloads"   # Final url will be like: # https://github.com/notepad-plus-plus/notepad-plus-plus/releases/download/v8.4.6/npp.8.4.6.portable.x64.zip
try {
    $page = Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 3
}
catch { 
    if ($_.Exception.Response.StatusCode -band 522) { "bad!"}
}

Solution

  • You should just call the current default error variable exception message/detail.

    $url = "https://notepad-plus-plus.org/downloads"   
    try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 3 -ErrorAction Stop}
    catch {$Error[0].Exception}
    # Results
    <#
    The operation has timed out.
    #>
    
    $url = "https://notepad-plus-plus.org/downloads"   
    try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -ErrorAction Stop}
    catch {$Error[0].Exception}
    # Results
    <#
    The remote server returned an error: (522).
    #>
    

    Thus do what you want based on that error message.

    $url = "https://notepad-plus-plus.org/downloads"   
    try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -ErrorAction Stop}
    catch
    {
        If (($Error[0].Exception) -match '522')
        {Write-Warning  -Message 'Bad stuff happened. Now, go do stuff'}
    }
    # Results
    <#
    WARNING: Bad stuff happened. Now, go do stuff
    #>
    

    Update

    Timeout check.

    $timer = [Diagnostics.Stopwatch]::StartNew()
    $url = "https://notepad-plus-plus.org/downloads"   
    try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 3 -ErrorAction Stop}
    catch 
    {
        $Error[0].Exception
        
        If (($Error[0].Exception) -match 'timed out')
        {Write-Warning  -Message 'Timeout occurred. Do you want to set a differnet timeout'}
    }
    $timer.Elapsed.TotalSeconds
    # Results
    <#
    The operation has timed out.
    WARNING: Timeout occurred. Do you want to set a differnet timeout
    3.0225485
    #>