Hi everyone!
These days I was looking for a script that could return me the last time my VMs were shut down by filtering their Events.
I found the one below:
function Get-LastPowerOff {
param(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true,
HelpMessage="VM"
)]
[VMware.VimAutomation.Types.VirtualMachine]
$VM
)
Process {
$patterns = @(
"*Power Off virtual machine*"
)
$events = $VM | Get-VIEvent
$qualifiedEvents = @()
foreach ($pattern in $patterns) {
$qualifiedEvents += $events | Where { $_.FullFormattedMessage -like $pattern }
}
$qualifiedEvents = $qualifiedEvents | Where { $_ -ne $null }
$sortedEvents = Sort-Object -InputObject $qualifiedEvents -Property CreatedTime -Descending
$event = $sortedEvents | select -First 1
$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name VM -Value $_
$obj | Add-Member -MemberType NoteProperty -Name PowerState -Value $_.PowerState
$obj | Add-Member -MemberType NoteProperty -Name LastPoweroff -Value $null
if ($event) {
$obj.LastPoweroff = $event.CreatedTime
}
Write-Output $obj
}
}
-----------------------------
Since I am pretty much new to Powershell / PowerCLI activities, I could not entirely understand the script at first sight. But I found out that I also needed to include the "Initiate guest OS shutdown" pattern in the highlighted part above. I want to know when the VM was turned off for the last time, not mattering if it was a "Power Off" or a Gracefull Shutdown. But I dont know how to include both in this same script. I tried the following:
Process {
$patterns = @(
"*Initiate guest OS shutdown*",
"*Power Off virtual machine*"
)
It wont bring me the last event by comparing both, but only using the first I declare (in the case above, "*Initiate guest OS shutdown*"), ignoring the date it could have been "Powered Off".
How can I make it work properly by considering both and bringing me the last event?
Thanks!!