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.

Create a scheduled task:
1
2
3
4
5
$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:\<path_to_file>\PingAppleSystemStatus.ps1 } -Trigger $dailyTrigger -ScheduledJobOption $option
</path_to_file>
The code below requires a little setup.
  • Set the SMTP Server
  • Change the 2 instances of someone@mail.com
PingAppleSystemStatus.ps1 Source:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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();
}
 
$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: