Guv
Enthusiast
Enthusiast

Powered off VM's and how long they have been powered off by.

Is it possible to get a script to show the powered off VM's in a cluster ande how long they have been powered off in days.

4 Replies
iw123
Commander
Commander

Hi,

To list powered off VMs you can use the following:

Get-VM | where {$_.PowerState -eq "PoweredOff"}

To list VMs that have been powered off for a certain length of time, the following posts should be of use:

http://communities.vmware.com/message/1674355

http://www.lucd.info/2010/02/09/events-part-5-powered-of-for-more-than-1-week/


Cheers!

*Please, don't forget the awarding points for "helpful" and/or "correct" answers
0 Kudos
LucD
Leadership
Leadership

You can use the following code

$vmOff = Get-Cluster MyCluster | Get-VM | where {$_.PowerState -eq "PoweredOff"}

Get-VIEvent
-Entity $vmOff -MaxSamples ([int]::MaxValue) | where {$_ -is [VMware.Vim.VmPoweredOffEvent]} | Group-Object -Property {$_.Vm.Name} | %{   $lastPO = $_.Group | Sort-Object -Property CreatedTime -Descending | Select -First 1 | Select -ExpandProperty CreatedTime
 
New-Object PSObject -Property @{     VM = $_.Group[0].Vm.Name
   
"Last Poweroff"= $lastPO
   
Duration = [math]::Round((New-TimeSpan -Start $lastPO | Select -ExpandProperty TotalDays))   } }


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

wreedMH
Hot Shot
Hot Shot

LucD,

From the code on your website, is it possible to add a column of the date it was powered off? Also only get VMs powered off LONGER than 30 days. This seems to be picking up VMs powered off today.

1

2

3

4

5

$vms = Get-VM | where {$_.PowerState -eq "PoweredOff"}

$vmPoweredOff = $vms | %{$_.Name}

$events = Get-VIEvent -Start (Get-Date).AddDays(-7) -Entity $vms | where{$_.FullFormattedMessage -like "*is powered off"}

$lastweekVM = $events | %{$_.Vm.Name}

$vmPoweredOff | where {!($lastweekVM -contains $_)}

0 Kudos
LucD
Leadership
Leadership

Try like this

$now = Get-Date

$vmOff = Get-Cluster MyCluster | Get-VM | where {$_.PowerState -eq "PoweredOff"}


Get-VIEvent -Entity $vmOff -MaxSamples ([int]::MaxValue) | where {$_ -is [VMware.Vim.VmPoweredOffEvent]} |

Group-Object -Property {$_.Vm.Name} | %{

  $lastPO = $_.Group | Sort-Object -Property CreatedTime -Descending | Select -First 1 | Select -ExpandProperty CreatedTime

  if((New-TimeSpan -Start $lastPO -End $now).TotalDays -gt 30){

   New-Object PSObject -Property @{

   VM = $_.Group[0].Vm.Name

   "Last Poweroff"= $lastPO

   Duration = [math]::Round((New-TimeSpan -Start $lastPO | Select -ExpandProperty TotalDays))

   }

  }

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos