Code to check for replication between two (or more) HyperV hosts, and restart replication on any critical VM’s.
This script can be run on a PDC or any HyperV server :
# Powershell Replication Health Script v2.00
# Written by Emil 02-12-2021
#
# SYNOPSIS
# This Powershell script will check through all the listed HyperV hosts for virtual machines
# with a replication status of Normal, Warning or Failed.
#
# Normal VM's will be listed in Green text.
#
# VM's whose replication was stopped manually, or have a warning flag set,
# will be displayed in Yellow, but will not be restarted.
#
# VM's with a critical status, where replication have stopped or broken,
# will be displayed in Red text, and the program will attempt to restart these.
#
# The program will also restart only the Primary (master) VM's and not
# any Replica VM.
#
#Clears the screen
Clear-Host -ForegroundColor White -BackgroundColor Black
#Edit the hosts below, change node1 and node2 to the names of your hosts. Do not use IP addresses.
$Hosts = "Labmaster","Labslave"
# Loops for each host listed above, and display which host it is on the screen
forEach ($server in $hosts)
{
Write-Host "----------------------------------"
Write-Host "Hyper-V Host : ", $server
Write-Host "----------------------------------"
# Here, we are invoking the Get-VMReplication CMDlet on the specified server,
# and get the information we require. We loop three times, once for Normal, once for Warning,
# and finally for Critical where replication have stopped.
Invoke-Command -ComputerName $Server {
$NormalReplicas = Get-VMReplication | Where {$_.Health -eq 'Normal' -and $_.Mode -eq 'Primary'}
ForEach ($VM in $NormalReplicas)
{
$vmname = $VM.Name
Write-Host "Virtual Machine : ", $VMName -ForegroundColor Green -BackgroundColor Black
Write-Host "----------------------------------"
}
}
Invoke-Command -ComputerName $Server {
$WarningReplicas = Get-VMReplication | Where{$_.Health -eq 'Warning' -and $_.Mode -eq 'Primary'}
ForEach ($VM in $WarningReplicas)
{
$vmname = $VM.Name
Write-Host "Virtual Machine : ", $VMName -ForegroundColor Yellow -BackgroundColor Black
Write-Host "----------------------------------"
}
}
Invoke-Command -ComputerName $Server {
$FailedReplicas = Get-VMReplication | Where{$_.Health -eq 'Critical' -and $_.Mode -eq 'Primary'}
ForEach ($VM in $FailedReplicas)
{
$vmname = $VM.Name
Write-Host "Virtual Machine : ", $VMName -ForegroundColor Red -BackgroundColor Black
Write-Host "----------------------------------"
# In order to prevent the command from trying to resume replicas and generating an error, we
# filter only for Primary VM's.
Resume-VMReplication $VMName -Resynchronize | where {$_.Mode -eq 'Primary'}
}
}
}
Write-Host "Run finished."
todo :
- add email notifications for VM’s that are in a critical state.
- see if the loops checking for conditions can be made more efficient