Anyone know how to check when a VMs in a cluster were last powered on/off/restarted, via a one line PowerCLI script? Googled and found a few examples of functions, but was hoping for something far simpler.
Something very vanilla, with output like > VM1 Last powered on 0129/2015 0450 HA restart
Finding out why the VM was last powered on/off would be nice as well.
Thanks.
Best way I can think of is searching for an event type of poweredon. It is however, limited by how much data the vCenter actually retains. So if vCenter prunes @ 180 days (typical), then if the VM were powered on 181 days ago, you'll have no events to know.
I use my own custom module to get events (very much like LucD's) zPowerCLI/Get-VIEventsFaster.ps1 at master · Zsoldier/zPowerCLI · GitHub
For example:
Import-Module Get-VIEventsFaster.ps1 #Assuming you downloaded and run it from the same directory.
$VMinQuestion = Get-VM thisGuyRightHere
$VMinQuestion | Get-VIEventsFaster -EventType @("VmPoweredOnEvent","DrsVmPoweredOnEvent")
Event Types are case sensitive, so watch out for that.
This'll return you all events associated w/ a powered on event and a powered on event handled by DRS.
Other event types you probably want:
VmGuestRebootEvent
VmGuestShutdownEvent
VmStoppingEvent
VmResettingEvent
You can find full list (related to VMs) here:
Other types, reference the "Extended by" Section:
Sorry don't have a one liner, I use this, give it a speed test - get-view is lighting fast - 500 vms in 5 seconds
<pre>
# Script to extract the last boot time of vms
# russ 11/08/2015
# Credits http://vmware-scripts.blogspot.com.es/2012/08/script-to-get-uptime-of-each-vm-in.html
# Create array to select the cluster
Clear
# Getting Cluster info
$Cluster
=
Get-Cluster
$countCL
= 0
Clear
Write-Output
" "
Write-Output
"Clusters: "
Write-Output
" "
foreach
(
$oC
in
$Cluster
){
Write-Output
"[$countCL] $oc"
$countCL
=
$countCL
+1
}
$choice
=
Read-Host
"On which cluster do you want to check the vm uptimes ?"
$cluster
=
get-cluster
$cluster
[
$choice
]
Write-Output
"$cluster `n............................................................"
# variable to associate date with boot time
$LastBootProp
= @{
Name =
'LastBootTime'
Expression = {
(
Get-Date
) - (
New-TimeSpan
-Seconds
$_
.Summary.QuickStats.UptimeSeconds )
}
}
# code; limits search for vms within cluster,
# filters for powered on vms, and sorts boot time in descending order
Get-View
-ViewType
VirtualMachine
-SearchRoot
(
get-cluster
-name
"$cluster"
).id `
-Filter
@{
"runtime.PowerState"
=
"poweredOn"
}
-Property
Name, Summary.QuickStats.UptimeSeconds `
| Select Name,
$LastBootProp
|
sort-object
-Descending
-Property
LastBootTime