Sunday, September 25, 2011

Test-Website

The following function might be useful for checking whether a web page is up or down in PowerShell:

function Test-Website([string][parameter(mandatory=$true)]$Url, [string]$Content)
{
    $webRequest = [System.Net.WebRequest]::Create($Url) 
    $webRequest.CookieContainer = New-Object System.Net.CookieContainer;
    
    try {
        $response = $webRequest.GetResponse() 
    }
    catch {
        return $false
    }
    
    if($response.StatusCode -ne 200) {
        return $false
    }
    
    $responseStream = $response.GetResponseStream()
    $sr = New-Object IO.StreamReader($responseStream)
    $result = $sr.ReadToEnd()

    return $result -match $Content
}

0 comments:

Post a Comment