Monday, 12 December 2022

Shutdown Date of Powered Off VMs using VMware PowerCLI

So you have got a list of Powered OFF VMs in vCenter and would like to perform a cleanup however you don't have any idea when this was powered OFF. Well there are three ways to find the powered OFF date.

1. Event Timestamp - highly reliable method 

2. NVRAM Timestamp - average reliable method

3. Storage Timestamp - least reliable method

Prerequisites 

Create a txt file named VMList.txt and paste the name of VMs one by one.

Step by Step Procedure

1. Save the VMList.txt in C:\Temp of your windows machine

2. Open PowerShell ISE and connect your vCenter

Connect-VIServer my-vcenter.xyz.intra

3. Input credentials and wait for the connection to establish.

4. Now paste the below script in the PowerShell ISE.

get-content "C:\Temp\VMList.txt" |

foreach {Get-VM -Name $_|

       Select Name,PowerState,

  @{N='Event Timestamp';E={

  (Get-VIevent -Entity $_ -MaxSamples ([int]::MaxValue) |

  where{$_ -is [VMware.Vim.VmPoweredOffEvent]} |

  Sort-Object -Property CreatedTime)[-1].CreatedTime

  }},

  @{N='Storage Timestamp';E={$_.ExtensionData.Storage.Timestamp.ToLocalTime()}},

  @{N='NVRAM Timestap';E={

  $dsName = ($_.ExtensionData.LayoutEx.File | where {$_.Type -eq 'nvram'}).Name.Split(' ')[0].Trim('[]')

  $ds = Get-Datastore -Name $dsName

  New-PSDrive -Location $ds -Name DS -PSProvider VimDatastore -Root "\" | Out-Null

  $file = Get-ChildItem -Path "DS:\$($_.Name)\$($_.Name).nvram"

  Remove-PSDrive -Name DS -Confirm:$false

  $file.LastWriteTime

  }} 

  } |Export-csv "c:\Temp\output.csv"

5. Select this Script in your PowerShell ISE and run this.


6. You will get the output in C:\Temp\output.csv in the below format.



Any questions, ask in comments.

Cheers!