Thursday, July 25, 2013

Powershell Script to Periodically Monitor a Web Page, Parse, and Notify

Since Apple's developer portals have been down for a while, I got tired of checking the website. I created a script that I will hourly check Apple's System Status page, parse and see if the iOS Developer Center is back online. If it is online, it will send an email to me letting me know and remove the scheduled task. The code could be repurposed to look for the other things in the html if needed.

First the scheduled task needs to be created, it requires a PowerShell console in Administrator mode.

$dailyTrigger = New-JobTrigger -RepetitionInterval (New-TimeSpan -Hours 1) -RepetitionDuration (New-TimeSpan -Days 7) -At "11:00 AM" -Once # -At 
$option = New-ScheduledJobOption -StartIfOnBattery –StartIfIdle
Register-ScheduledJob -Name PingAppleSystemStatus -ScriptBlock `
{ powershell -command C:\\PingAppleSystemStatus.ps1 } -Trigger $dailyTrigger -ScheduledJobOption $option
The code below requires a little setup.
  • Set the SMTP Server
  • Change the 2 instances of someone@mail.com
function Send-Email([string] $From, $To, [string] $Subject, [string] $Body, $AttachmentPaths = $null, [bool] $IsImportant = $FALSE) {
 $msg = new-object Net.Mail.MailMessage;
 $smtp = new-object Net.Mail.SmtpClient("yoursmtpserver.com");
 $atts = @();
 $msg.From = $From;
 $To | % { $msg.To.Add($_); }
 $msg.Subject = $Subject;
 $msg.Body = $Body;
 if ($AttachmentPaths -ne $null) {
  $AttachmentPaths | % {
   $att = new-object Net.Mail.Attachment($_);
   $msg.Attachments.Add($att);
   $atts += $att;
  }
 }
 if ($IsImportant) {
  $msg.Priority = [System.Net.Mail.MailPriority] "High";
 }
 $smtp.Send($msg);

 $atts | % { $_.Dispose(); }
 $msg.Dispose();
}

$url = 'https://developer.apple.com/support/system-status/';
$result = Invoke-WebRequest $url;
$foundElement = $result.AllElements | 
    Where Class -eq "online" | 
    Where innerText -eq "iOS Dev Center" | 
    Select -ExpandProperty innerText;

if ($foundElement) {
 Write-Host "$([DateTime]::Now) - iOS Dev Center LIVE";
 Send-Email "Me <someone@mail.com>" @("<someone@mail.com>") "$([DateTime]::Now) - iOS Dev Center LIVE" "$([DateTime]::Now) - iOS Dev Center LIVE" $null $TRUE;
 Unregister-ScheduledJob  -Name PingAppleSystemStatus
} else {
 Write-Host "$([DateTime]::Now) - iOS Dev Center Offline";
}

No comments: