Powercli Find Powered Off VM and shutdown date

aztech picture aztech · Apr 27, 2018 · Viewed 8.4k times · Source

I have a generic script that will show me all powered off vm's on a singular host. I would like to build upon that and have it show me what date it was powered off so we know how long it's been off for. Below is the script i'm using that shows me powered off vm's on a singular host:

get-vm -location host.domain.com | ?{$_.PowerState -eq "PoweredOff"}

I can easily add multiple hosts separated by a comma and get all powered off vm's for those hosts listed out.

Also, if anyone knows of a way for me to bypass doing this one host at a time and have it check all hosts in my vcenter that would be awesome

Thanks in advance :)

Answer

TessellatingHeckler picture TessellatingHeckler · Apr 28, 2018

I don't think there is a property recording when they were powered off. You will have to read the VMware task and event log for each VM and look for 'shutdown' or 'powered off' messages, and pick the most recent one.

Get-VM | 
    Where-Object -Property PowerState -eq 'PoweredOff' | 
    Select-Object -Property Name, @{Label='poweredOffTime'; Expression={
        $_ | Get-VIEvent -Types Info | 
            Where-Object -Property fullformattedmessage -Match 'shutdown|powered off' | 
            Sort-Object -Property CreatedTime | 
            Select-Object -Last 1 -ExpandProperty CreatedTime 
    }}

But that will only work if the logs go back far enough to record the shutdown/power off events, if it happened past the log clearout time, you might be out of luck.

NB. I'm not sure 'shutdown|powered off' will get every related message, it should cover "Initiate guest OS shutdown" and "{VM} on {host} in {site} is powered off" logs.