#requires -version 2.0 #script parameter Param([string[]]$url=$(Throw "You must specify a URL like http://www.microsoft.com"), [string]$log="c:\logs\webping.csv", [string]$to="jhicks@jdhitsolutions.com", [string]$from="jhicks@jdhitsolutions.com", [string]$subject="Web Site Status Report", [string]$smtpServer="mail.jdhitsolutions.com", [system.Management.Automation.PSCredential]$mailcred, [switch]$verbose ) 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 #Main script code if ($verbose) { $verbosePreference="Continue" Write-Verbose "Starting script" $data = $url | Test-Website -verbose } else { $data = $url | Test-Website } $msg=@() #convert to CSV $csv = $data | ConvertTo-Csv -NoTypeInformation #if $log doesn't exist, create it with $log If (-not (Test-path $log)) { Write-Verbose "Creating $log" $csv | Set-Content -Path $log } #otherwise append entries and skip header else { Write-Verbose "Appending data to $log" $csv | Select-Object -Skip 1 | Add-Content -Path $log } #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 Write-Verbose "Ending script" #end of script