Showing posts with label monitor. Show all posts
Showing posts with label monitor. Show all posts

Thursday, 6 May 2021

Monitoring Hyper-V to Azure Site Replication with Powershell

Here is a simple script that I use to monitor the replication state of Hyper-V servers that I have replicated to Azure using Site Replication.

I have this script run every morning as a scheduled task which sends me an email with a nicely formatted table showing the replication status of all of my Hyper-V VM's to Azure

I have 4 Hyper-V nodes in a cluster - I have specified the 4 node names individually and used a ForEach loop to cycle through them all the generate the report. You can remove the loop if you're only using this for a single server/host.

(You will need to have the Hyper-V powershell module/cmdlets installed for this to work)

import-module Hyper-V -RequiredVersion 1.1
$repstate = @()
$date = get-date -f "dd-MM-yyyy"
$clusternodes = "node1", "node2", "node3", "node4"

foreach ($node in $clusternodes)
    {
    $repstate += get-vmreplication -computername $node | select Name, State, Health, Mode, FrequencySec, PrimaryServer, ReplicaServer, PrimaryServerName, LastReplicationTime
    }

You can then export the values from the $repstate variable to a CSV file and attach it, or as I have done, convert it to HTML and set it to the body of an email message

$mailmessage.Body = $repstate | ConvertTo-HTML -fragment



Tuesday, 20 September 2016

IP Address/Ping Monitoring using Powershell

Here is a script I developed to monitor/check the online availability of an IP address using powershell. I've set this script to run every 10 minutes to check that a device on my network (WDTV Live) is online as it had a tendency to go offline occasionally.

$ip = the IP address you wish to monitor
$ping = utilises the test-connection cmdlet to attempt to contact the IP address (specified in $ip) using ICMP (ping) packets

If the ping test does not return a result (ie. the IP address does not respond), a "flag" is placed in the form of a file called "WDTV.Offline". This flag file is used/checked by the script to prevent repeat notifications being sent after the first notification that the device is offline (or is back online after previously being offline)

If the ping test does return a result (ie. the IP address responded to the ping request), the script checks to see if it was previously offline (by looking for the flag file mentioned previously). If the flag file is found, another notification is sent advising the device is now back online, and the flag file is deleted. This means the next time the script runs, if the device is still online and no flag file is present, no further notifications are sent


$ip = "192.168.0.150"
$ping = test-connection $ip -count 2

if (!$ping)
    {
    $flagtest = test-path "D:\Powershell\WDTV.Offline"
    if ($flagtest -eq $false)
        {
        new-item "D:\Powershell\WDTV.Offline" -type file
        $from = "user@gmail.com"
        $to = "user@gmail.com"
        $subject = "$ip Offline"
        $body = "$ip not responding to ping"
        $smtp = New-Object System.Net.Mail.SmtpClient("smtp.gmail.com", "587");
        # Uncomment the below row if your ISP´s outgoing mail server requires authentication.
        $smtp.EnableSSL = $true
        $smtp.Credentials = New-Object System.Net.NetworkCredential("username", "password");
        $smtp.Send($From, $To, $subject, $body);
        #write-host "Mail Sent"
        }
    }

elseif ($ping)
    {
    $flagtest = test-path "D:\Powershell\WDTV.Offline"
    if ($flagtest -eq $true)
        {
        remove-item "D:\Powershell\WDTV.Offline"
        $from = "user@gmail.com"
        $to = "user@gmail.com"
        $subject = "$ip Online"
        $body = "$ip now responding to ping"
        $smtp = New-Object System.Net.Mail.SmtpClient("smtp.gmail.com", "587");
        # Uncomment the below row if your ISP´s outgoing mail server requires authentication.
        $smtp.EnableSSL = $true
        $smtp.Credentials = New-Object System.Net.NetworkCredential("username", "password");
        $smtp.Send($From, $To, $subject, $body);
        #write-host "Mail Sent"
        }
    }

You will need to update the $from, $to and username/password fields within the $smtp.credentials variables in order for the email notifications to work, as well as the values for outgoing mail server and port within the System.Net.Mail.SmtpClient

You can refer to my previous blog post Here which contains some more information about sending SMTP emails using authentication with powershell

Friday, 28 March 2014

Check/Monitor Website URL with Powershell

Windows Powershell has a built in web request module that you can use to test/check the availability of website URL(s).

The full script to do this is below;

[string] $url = "http://www.google.com"
[net.httpWebRequest] $req = [net.webRequest]::create($url)
$req.method = "HEAD"
[net.httpWebResponse] $res = $req.getresponse()

The first line is self explanatory - simply put in the full URL for the website you wish to check. In this example we will be checking http://www.google.com

[string] $url = "http://www.google.com"

The second line is where we create the actual web request instance in Powershell - under the $req variable

[net.httpWebRequest] $req = [net.webRequest]::create($url)

On the third line, we change the request method to be "HEAD" which means that only header information for the requested URL is retrieved. This speeds up the web request process as it does not pull all the data from the web URL - only the header information. If you leave this line out, the default method is "GET".

$req.method = "HEAD"

On the last line we actually submit the web request, and store the response in the $res variable

[net.httpWebResponse] $res = $req.getresponse()

For a successful web request, the response should look something like this:

IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {Cache-Control, Content-Type, Date, Expires...}
ContentLength           : -1
ContentEncoding         : 
ContentType             : text/html; charset=ISO-8859-1
CharacterSet            : ISO-8859-1
Server                  : gws
LastModified            : 28/03/2014 10:24:19 AM
StatusCode              : OK
StatusDescription       : OK
ProtocolVersion         : 1.1
ResponseUri             : http://www.google.com.au/?gfe_rd=cr&ei=I7M0U5P_BenC8gfRvIHADg
Method                  : HEAD
IsFromCache             : False

Based on this, you could check the statuscode or statusdescription properties of $res to make sure the value matches "OK".

Alternatively, if you enter an invalid URL for a website that doesn't exist, you will get an error, and the value of $res will be $null. The error you get will be something along the lines of;

Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (502) Bad Gateway."
At line:4 char:46
+ [net.httpWebResponse] $res = $req.getresponse <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException