PowerShell script that checks the status of a web server

Here’s a PowerShell script that checks the status of a web server by running a report, highlights any 503 errors in yellow with bold red font, and sends the results via email as an HTML table to IT Support. This script assumes you have the necessary permissions and configurations for email sending and server access.
# Define variables $websites = @( "https://example1.com", "https://example2.com" ) $report = @() $from = "monitoring@example.com" $to = "itsupport@example.com" $smtpServer = "smtp.example.com" $smtpPort = 587 $smtpCredential = New-Object System.Management.Automation.PSCredential("username", (ConvertTo-SecureString "password" -AsPlainText -Force)) # Check website status foreach ($site in $websites) { try { $response = Invoke-WebRequest -Uri $site -UseBasicParsing -TimeoutSec 10 $status = $response.StatusCode $statusDescription = $response.StatusDescription } catch { $status = $_.Exception.Response.StatusCode.Value__ $statusDescription = $_.Exception.Response.StatusDescription } $report += [PSCustomObject]@{ Website = $site StatusCode = $status StatusDescription = $statusDescription } } # Generate HTML report $htmlReport = @" <html> <head> <style> table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid black; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } .error { background-color: yellow; color: red; font-weight: bold; } </style> </head> <body> <h2>Website Status Report</h2> <table> <tr> <th>Website</th> <th>Status Code</th> <th>Status Description</th> </tr> "@ foreach ($entry in $report) { $rowClass = if ($entry.StatusCode -eq 503) { "error" } else { "" } $htmlReport += "<tr class='$rowClass'><td>$($entry.Website)</td><td>$($entry.StatusCode)</td><td>$($entry.StatusDescription)</td></tr>" } $htmlReport += @" </table> </body> </html> "@ # Send email Send-MailMessage -From $from -To $to -Subject "Website Status Report" -Body $htmlReport -BodyAsHtml -SmtpServer $smtpServer -Port $smtpPort -Credential $smtpCredential -UseSsl
How It Works:
- Website Check: The script loops through a list of websites, checking their status using
Invoke-WebRequest
. If a 503 error occurs, it captures the status code and description. - HTML Report: It dynamically generates an HTML table. Rows with a 503 error are styled with a yellow background and bold red font.
- Email Sending: The
Send-MailMessage
cmdlet sends the HTML report to the specified IT Support email.
Prerequisites:
- Replace placeholders like
smtp.example.com
,username
, andpassword
with your actual SMTP server details and credentials. - Ensure the
Send-MailMessage
cmdlet is supported in your environment. If not, consider using an alternative email-sending method likeMailKit
.
This script is adaptable and should help you monitor web server statuses effectively!