Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Hey, are you awake?

Posted on April 7, 2010

Validated01 As many of you know, one of the things I’m doing these days is helping run The Experts Community web site. As such I need to make sure it is up and running. I also like to make sure my blog and a few other sites are responding to HTTP requests. To meet this need I put together a PowerShell function to test a web site and determine if it is running or not.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

There are no cmdlets from Microsoft for testing web site connectivity. However, there is a .NET class called System.Net.WebRequest. I put together a short 2.0 function that uses this class and returns a custom object to the pipeline.

Function Test-WebSite {            
    [cmdletBinding()]            
    Param (            
          [Parameter(            
           ValueFromPipeline=$True,Position=0,Mandatory=$True,            
           HelpMessage="The URL to test. Include http:// or https://")]            
           [string]$url            
           )            
            
    Begin {            
        Write-Verbose "Begin function"            
        }            
    Process {            
        Write-Verbose "Requesting $url"            
                    
        $wr=[system.net.webrequest]::Create($url)                 
        #set timeout to 7 seconds            
        $wr.Timeout=7000            
        $start=Get-Date            
                    
        Try {            
            $response=$wr.GetResponse()            
            if ($response) {            
                 Write-Verbose "Response returned"            
                $Status=$response.StatusCode            
                $StatusCode=($response.Statuscode -as [int])            
            }            
        }            
        Catch  [system.net.webexception] {            
            Write-Verbose "Failed to get a response from $url"            
            Write-Warning "Failed to get a response from $url"            
            $status =  $_.Exception.Response.StatusCode            
            $statuscode = ( $_.Exception.Response.StatusCode -as [int])            
        }            
                    
        $end=Get-Date            
        $timespan=$end-$start            
        $ResponseMS=$timespan.TotalMilliseconds            
                          
        Write-Verbose "status is $status"            
        Write-Verbose "statuscode is $statuscode"            
        Write-Verbose "timer is $responseMS"            
                    
        $obj=New-Object PSObject -Property @{            
            DateTime=$start            
            URL=$url            
            Status=$status            
            StatusCode=$statuscode            
            ResponseMS=$ResponseMS            
         }            
         Write-Output $obj            
                     
      } #end Process            
     End {            
        Write-Verbose "End function"            
     }            
} #end function

The function takes a URL to test and it can be piped. Using a Try/Catch construct the function attempts to get a response from the site. If it fails, then a System.Net.WebException object is caught so I can grab the status code (eg 404 or 500).

The .NET class doesn’t include a property to capture how long the response took, at least not that I can discover. So instead I simply get the time, attempt the request, get the time again and calculate the difference. Close enough for my needs. FInally, the function writes a custom object to the pipeline using New-Object.

When the function is loaded you can run it like this:

PS C:\> test-website https://jdhitsolutions.com/blog

ResponseMS : 253.0145

StatusCode : 200

Status     : OK

URL        : https://jdhitsolutions.com/blog

DateTime   : 4/7/2010 11:04:30 AM

With this in place, I then turned to the notification process. Windows PowerShell 2.0 includes a cmdlet, Send-MailMessage, which can deliver an SMTP message. My script runs through a list of URLs, saves the objects to a variable, which I then parse out to build a message string. Each URL has its own message which is temporary stored in an array. Then the array is converted to a string and used as the message body for my email notification.

#build message string for email           
$data | foreach {           
    $m=("{0} {1} {2} ({3}) {4} milliseconds" -f `

      $_.DateTime,$_.url,$_.status,$_.StatusCode,$_.ResponseMS)            
    Write-Verbose "Building message string"             
    Write-Verbose $m             
    $msg+=$m            
}            
            
#send mail response            
Write-Verbose "Sending mail message"            
Send-MailMessage -To $to -From $from -Subject $subject `
-Body $($msg |out-string) -SmtpServer $smtpServer -credential $mailcred            

Depending on your SMTP server configuration you may or may not need to specify a credential. Your SMTP server may also need some minor reconfiguration depending on your network.

The last step was to simply create a scheduled task to run my PowerShell script:

powershell.exe -noprofile -noninteractive -file c:\scripts\ScheduledWebCheck.ps1

Now I get an hourly report that lets me know the web site status, which thankfully is almost always up.


Behind the PowerShell Pipeline
Download Test-Web.ps1

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

1 thought on “Hey, are you awake?”

  1. jv says:
    April 7, 2010 at 10:38 am

    Jeff see:

    http://www.scriptinganswers.com/forum2/forum_posts.asp?TID=3744

    Tis might be of interest for a future blog as your above bolg solves a couple of problems but does not discover the rediredcted URL. I looked for a quick way in VBS but didn’t find one. Haben’t looked at PowerShell for a solution.

    Also the following might be interesting for your IIS Admin blogs. It’s AD/PowerShell/IIS related.

    http://www.scriptinganswers.com/forum2/forum_posts.asp?TID=3757

    GL

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d