, ,

PS | How to get HA restarted VM's Org and OrgvDC info with VM Name

Overview

You will see many blogs giving solution for fetching the VM names which are restarted by HA in event of esxi host failures using Get-VIEvent powercli command. But the extracted VM Name too is not in well format to use as it is. You have to use excel and text to column and then extract the VM Name etc. For me, I have vCD also so at the time of ESXi host failures and HA events, I not only need to fetch the VM Name but also Org and OrgvDC info to share it with my customer. It becomes more lengthy for me and I need to make it quick. So it is extended solution for such kind of scenario. Hope you will find it useful.

Let's see how I could do it using powershell.

Script

#Start here

Write-Host "This script will help you out to have VM name restarted by HA due to esxi host failuers" -ForegroundColor Yellow

Function Get-HAVM{
$Date=Get-Date
$HAVMrestartold=1
$raw = Get-VIEvent  -maxsamples 10000000 -Start ($Date).AddDays(-$HAVMrestartold) -type warning | Where {$_.FullFormattedMessage -match "restarted"} |select CreatedTime,FullFormattedMessage |sort CreatedTime -Descending
$raw.vm.name
Remove-Item -Path C:\Temp\vmlist.csv
$raw.vm.name | Out-File C:\Temp\vmlist.csv
}
Get-HAVM
$allvms = Get-Content -Path C:\Temp\vmlist.csv
$vms = Get-VM -Name $allvms
$myView = @()
foreach ($vm in $vms){
$Report = [PSCustomObject] @{
 VM_Name = $vm.Name
 Org_Name = $vm.Folder.Parent.Parent.Name
 OrgvDC_Name = $vm.Folder.Parent.Name
}
$MyView += $Report
}
$myView | Out-GridView

#End here

Any doubt? Comment box is yours :)

Let's give it more power

If you have smtp configured in your environment then simply you can mail it from the same script using Send-MailMessage command but for that you might have to do some tweak in above script. 

Hint is, You have to save final report. Change in the last line of above script like

$myView | Out-File C:\Temp\vmsrestartedbyHA.csv

then use below command

Send-MailMessage -From 'gautam.johar@vcnotes.in' -To 'my.reader@home.com', 'myreader2@home.com' -Subject 'HA Event is triggered and VM list is attached' -Body "Please find the attachment" -Attachments C:\Temp\vmsrestartedbyHA.csv -Priority High -DeliveryNotificationOption OnSuccess, OnFailure -SmtpServer 'smtp.vcnotes.in'

Change wherever applicable.

If you are good enough in PowerShell then you can have many ways to enhance the ideas. For me this is basic script which is working fine for me.

Side Note

I created this script to run perfectly in PowerShell ISE so run in that please or if you have any error in running it in simple powershell cli terminal then you might need to fix the visible errors.

Good Luck!









0 Comments:

Post a Comment