Friday, February 27, 2015

Windows PowerShell script to check the website status!



Description:
This is a small PowerShell script; you can run it from your any windows machine to check your or any website’s status in every 30 seconds/ any at frequency. (you can change it to your desire time)
And if it (script) found that the specific webpage is down then it will send you an email that your web site is down.
But you need a SMTP server and internet connection. 

Use case:  

If is there any scenarios come like, your webpage is going down any how without your knowledge and you are getting so many complain about it. Then you can implement this script to monitor your site and take necessary actions. 

Here I have used web page as an "https://www.facebook.com/" and it will check the status of this page or link in every 30 seconds.  

The Script:

 Begin {  
   $web = New-Object System.Net.WebClient  
   $web.UseDefaultCredentials = $True  
   $flag = $false  
   $url = "https://www.facebook.com/"  
   }  
 Process {  
   While ($flag -eq $false) {  
     Try {  
       $web.DownloadString($url)  
       clear  
     Write-Host -ForegroundColor Green "$(Get-Date): Facebook is up!"  
     Start-Sleep -Seconds 30  
      ##  $flag = $True  
       }  
     Catch { Write-host -fore Red "$(Get-Date): Facebook is down..."   
      ## email sending----------------  
     $emailFrom = "Halim@test.com"  
     # Use commas for multiple addresses  
     $emailTo = "Halim@test.com,halim1@test.com"  
     $subject = "Facebook May be Down(Test email notification system) !!"  
     $body = "Facebook May be Down. Please Check! (This is just a test email)" # Details: $($_.Exception)"  
     $smtpServer = "192.168.10.199" # your smtp server's IP or name.   
     $smtp = new-object Net.Mail.SmtpClient($smtpServer)  
     $smtp.Send($emailFrom, $emailTo, $subject, $body)    
     $flag = $True  
     ##exit   
        ## -----------------------  
           }  
                }  
      }    
 End {  
   Write-Host -fore yellow "Email send & This process need to run again for further monitoring"  
   }  


How  to execute or run :
            1) Go to search or run and type “PowerShell”  enter  or go to the following exe,  then click
                %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
           2)  Copy & paste the code on it, then enter.


Thanks
Halim

No comments: