Search code examples
powershellwebhttpwebrequestwebrequestpowershell-ise

PowerShell ISE WebRequest fails after multiple calls


The following code works by itself if running from a console, but when running it using PowerShell ISE, it fails with Exception calling "GetResponse" with "0" argument(s): "The operation has timed out" after two runs. Have to restart the ISE to run it again.

$req = [System.Net.WebRequest]::CreateHttp("http://stackoverflow.com/")
$req.Timeout = 500
$req.GetResponse()

What is this limitation and is there a way to remove the limitation?


Solution

  • It seems like you have to dispose the response:

    $req = [System.Net.WebRequest]::CreateHttp("http://stackoverflow.de/")
    $req.Timeout = 5000
    $response = $req.GetResponse()
    
    $response.Dispose()
    

    However, there is a built-in cmdlet Invoke-WebRequest which you could also use:

    Invoke-WebRequest http://stackoverflow.de/