Check Hyper-V replication status with Powershell
Setting up Hyper-V replication is a quick way to gain redundancy. The setup is quite straightforward but will not be covered in this guide.
To keep track of the replication it would be nice to have it automated and that you will be notified if something goes wrong. A weekly update in general is also a nice thing. Therefore I wrote the little script below:
# Script that checks the status of the VM replication and emails in case of an error.
#Written by Drakfot
#ChangeLog:
#20140304 – Initial scripting started.
#Variables
$VMSERVER = "Your.Server.here" #Make sure to use a FQDN here, otherwise the email function will fail!
$VMSTATUS = Measure-VMReplication -ComputerName $($VMSERVER)
#Have a specific funtion for the Email
Function Email_Info {
Param($Name,$Status,$Type) #Required input for the function.
#Variables
$SMTPSERVER = "Your.SMTP.Server"
$EMAILTO = "Your.EmailAddress"
$EMAILFROM = "Admin@$($VMSERVER)"
#Send the message if an error has occurred
if ($Type -eq "Error") {
$EMAILBODYMESSAGE = " The replication of server $($Name) is $($Status)! `n Check the status by running Get-VMReplication -ComputerName $($VMSERVER) -VMName $($Name)"
Send-MailMessage -SmtpServer $($SMTPSERVER) -To $($EMAILTO) -Subject "$($Name) has replication status: $($Status)!" -Body "$($EMAILBODYMESSAGE)" -from "$($EMAILFROM)"
}
if ($Type -eq "Status"){
$EMAILBODYMESSAGE = $VMSTATUS | out-string
Send-MailMessage -SmtpServer $($SMTPSERVER) -To $($EMAILTO) -Subject "$($VMSERVER): Hyper-V replication status" -from "$($EMAILFROM)" -Body "$($EMAILBODYMESSAGE)"
}
}
# If we just want to send current status via email this function triggers it
if ($args -eq "Status"){
Email_Info -Type "Status"
}
#Loop through the array of replicated servers and check their current status
For ($i=0; $i -lt $VMSTATUS.Length; $i++) {
if ($VMSTATUS[$i].Health -ne "Normal") {
#If something is wrong we want to know it, therefore we email it using the function created above!
Email_Info -Name $($VMSTATUS[$i].Name) -status $($VMSTATUS[$i].Health) -Type "Error"
}
}
What it does is that it uses the Measure-VMReplication cmdlet (of course you can also use the Get-VmReplication cmdlet) and stores the result in an array. This array is then looped through checking the “Health” part to see if it is “Normal” or not. If not an email will be sent to the recipient specified in the script.
Also, if the script is called with the “status” argument it will send a summary (basically the output of the $VMSTATUS array) to the email specified. This in case a daily/weekly/monthly/yearly status is wanted.