Monitor SharePoint (and general web pages) for changes with PowerShell

If you need to monitor SharePoint page content (or any other web page requiring authentication for that matter) for changes, you can consider running the following PowerShell on a periodic basis with Windows Task Scheduler. This PowerShell:

– Fires up the System.Net.WebClient object
– Uses the supplied $Username, $Password and $Domain credentials to login to the page specified in the $url parameter
– Parses the page looking for the string specified in the $Results.Contains(“my string”)
– If the string is not found, fire off an email using the the $subjectnew, $fromAddress, $smtpServerName and $toAddress parameters

         $url = ""
         $Username = "johnsmith"            
         $Password = "mypassword"   
         $Domain = "mydomain"
         $WebClient = New-Object System.Net.WebClient  
         $webclient.Headers.Add("user-agent", "Powershell webclient")
         $WebClient.credentials = New-Object System.Net.NetworkCredential -ArgumentList $Username, $Password, $Domain    
         $Results = $WebClient.DownloadString($url)
         $subjectnew = "String is missing from page $url"
         $fromAddress = ""
         $smtpServerName = ""
         $toAddress = ""
         $IsStringThere = $Results.Contains("my string")
                 If (!$IsStringThere){
                          # You could execute something here to log positive hit on string
                          Send-MailMessage –From $fromAddress –To $toAddress –Subject $subjectnew –Body "$(Get-Date) String was not found on page: $url" –SmtpServer 

Some notes:
– storing user credentials directly in PowerShell is generally a no-no. There’s better ways to pass in credentials but for the purpose of simplicity i’ve omitted them from this example. Use as-is at your own peril!
– this method parses the entire page HTML source output, which can be good or bad depending on what you’re trying to monitor. Carefully analyze what specific string you’re looking for before relying on this.
– clearly there is overhead to the operations involved in this. If you’re monitoring a page for defacement or such a 30 minute interval in the Windows Task Scheduler should be plenty. Use perfmon or whatever performance monitoring tool exists on your target server to ensure that you are not using up excess resources

Leave a Reply

Twitter feed is not available at the moment.