1

Closed

Need to close response object

description

I noticed the script would randomly hang when there were a lot of sites. The solution is to close the web response like this (see the finally block at the end)
Function Web-RequestUrl([string] $Url)
{
    $TimeStart = Get-Date
    $WebRequestObject = [System.Net.HttpWebRequest] [System.Net.WebRequest]::Create($Url)
    $WebRequestObject.UseDefaultCredentials = $true
    $WebRequestObject.Method = "GET"
    $WebRequestObject.Accept = "text/html"
    $WebRequestObject.Timeout = 80000

    Write-Host -ForegroundColor White " - Web Request for url: $url"
    $global:MailContent += " - Web Request for url: $url"
    try
    {
        # Get the response of $WebRequestObject
        $ResponseObject = [System.Net.HttpWebResponse] $WebRequestObject.GetResponse()
        $TimeStop = Get-Date
        $TimeExec = ($TimeStop - $TimeStart).Seconds
        Write-Host -ForegroundColor Green "  WebSite successfully loaded in $TimeExec s"
        $global:MailContent += "<br><font color=green>WebSite successfully loaded in $TimeExec s</font><br>"
    }
    catch [Net.WebException]
    {
        $ExceptionText = $_.Exception.Message
        write-Host -ForegroundColor Yellow $ExceptionText
        $global:MailContent += "<br><font color=red>$ExceptionText</font><br>"
    }
    finally 
    {
        if ($ResponseObject) 
        {
            $ResponseObject.Close()
            Remove-Variable ResponseObject
        }
    }
}
Closed Sep 19, 2014 at 3:32 PM by Luigilink

comments

Luigilink wrote Sep 1, 2014 at 9:18 AM

Yes, very good idea !
Thanks you so much for you help, I'll fix this in the next release.

wrote Sep 19, 2014 at 2:23 PM

wrote Sep 19, 2014 at 3:32 PM

wrote Sep 19, 2014 at 3:32 PM