Today I wanted to make automated monitor script which monitors Virtual Machine states and alerts me if something is not normal. Here is what I came up with:
$vms = Get-VM -ComputerName s2012-hv01,s2012-hv04,HV02Code will check some states and send an email if something is not right. I added this to task scheduler and run it as administrator (user which is not logged on normally) on startup + repeat every 30mins. Commented line is for messagebox but I was not able to use it on task scheduler, thus mail.
$warningMessage='';
foreach ($vm in $vms)
{
if ($vm.Status -ne "Operating normally")
{
$warningMessage += "`n$($vm.name) [$($vm.ReplicationMode)] is not operating normally on $($vm.ComputerName), status: $($vm.status)! "
}
elseif ($vm.ReplicationState -ne "Replicating")
{
$warningMessage += "`n$($vm.name) [$($vm.ReplicationMode)] has invalid replication state($($vm.ReplicationState)) on $($vm.ComputerName)! "
}
elseif($vm.MemoryStatus -ne 'OK' -and $vm.MemoryStatus -ne '')
{
$warningMessage += "`n$($vm.name) [$($vm.ReplicationMode)] has invalid memory status($($vm.MemoryStatus)) on $($vm.ComputerName)! "
}
elseif($vm.ReplicationHealth -ne "Normal")
{
$warningMessage += "`n$($vm.name) [$($vm.ReplicationMode)] does not have healthy replication status($($vm.ReplicationHealth)) on $($vm.ComputerName)! "
}
}
if ($warningMessage -ne '')
{
#[System.Windows.Forms.MessageBox]::Show("Replikoinnissa on virhe. $warningMessage","Virtual machine issue!")
Send-MailMessage -To "ex.ample@example.fi" -From "monitor@example.fi" -Body "Virtual machine issue`n$warningMessage`n`n" -Subject "Virtual machine issue" -SmtpServer "smtp.example.fi" -Encoding UTF8
}