I have been asked to write a script to find out who created a particular VM or get a list of VMs that were built in the last N days…
Again, we need to go through the vCenter database and search for a particular event type or name. Cmdlet that is going to help us is Get-VIEvent
, well documented <here>.
Next step is to filter Events of a particular type/name. Get-VM | Get-VIEvent -Types Info | Where {$_.Gettype().Name -eq "VMEvent"}
. Full list of virtual machine VM events is available at the bottom of this post.
What VM events correspond to VM deployment? Well, you can create, register or deploy VM from a template / clone VM. All these actions have corresponding VM Events but not all of them give us the information that we need:
- “
VmClonedEvent
” records the event when VM has been cloned but does not tell you what VM it has been cloned to:UserName CreatedTime FullFormattedMessage -------- ----------- -------------------- vStrong.localzmark.strong 30/09/2013 13:52:44 Clone of DDC1EDI002 completed
This VM Event is useful if you want to check whether the cloning/deploying from a template was successful. I am more interested in what VM the template has been cloned to, not the fact that the template has been cloned, therefore, I will not include “
VmClonedEvent
” in my script. - “
VmDeployedEvent
” only tells you that VM has been deployed from a template but does not tell you what template is got deployed from:UserName CreatedTime FullFormattedMessage -------- ----------- -------------------- vStrong.localzmark.strong 13/09/2013 11:50:57 Template tdc1orac002n002 deployed on host ddc1vexc01n02.vStrong.local
If you use “
VmBeingDeployedEvent
“, you get a the information what template VM gets deployed from:UserName CreatedTime FullFormattedMessage -------- ----------- -------------------- vStrong.localzmark.strong 13/09/2013 11:48:25 Deploying tdc1orac002n002 on host ddc1vexc01n02.vStrong.local in DC1 from template TestOracleCluster
You also can run a query to check if the VM deployment was successful…
OK, here is “Who created this VM” script?
Get-VM -Name MyVM | Get-VIEvent -Types Info |` Where {` $_.GetType().Name -eq "VmBeingDeployedEvent"` -or $_.GetType().Name -eq "VmCreatedEvent"` -or $_.GetType().Name -eq "VmRegisteredEvent"} |` Select UserName, CreatedTime, FullFormattedMessage | FT -AutoSize
VM created in the last seven days:
$CDT = Get-Date # CDT stands for 'Current Date and Time' :) Get-Cluster -Name MyCluster | Get-VM |` Get-VIEvent -Types Info -Start $CDT.AddDays(-7) -Finish $CDT |` Where {` $_.Gettype().Name -eq "VmBeingDeployedEvent"` -or $_.Gettype().Name -eq "VmCreatedEvent"` -or $_.Gettype().Name -eq "VmRegisteredEvent"} |` Select UserName, CreatedTime, FullFormattedMessage | Format-Table -AutoSize
Script output:
UserName CreatedTime FullFormattedMessage -------- ----------- -------------------- vStrongzMark.Strong 13/09/2013 11:48:25 Deploying tdc1orac002n002 on host ddc1vexc01n02.vStrong.local in DC1 from template TestOracleCluster vStrongzMark.Strong 17/09/2013 16:56:50 Registered Lost_and_Found on ddc1vexc01n02.vStrong.local in DC1 vStrongzSvcTrendMicro 18/08/2013 18:14:09 Created virtual machine dsva-ddc1vexc01n02 on ddc1vexc01n02.vStrong.local in DC1
You can also amend the script as the following:
$CDT = Get-Date # CDT stands for 'Current Date and Time' Get-VM | Get-VIEvent -Types Info -Start $CDT.AddDays(-7) -Finish $CDT |` Where {$_ -is [Vmware.vim.VmBeingDeployedEvent]` -or $_ -is [Vmware.vim.VmCreatedEvent]` -or $_ -is [Vmware.vim.VmRegisteredEvent]}|` Select UserName, CreatedTime, FullFormattedMessage
You can get / refer to VM name as ‘$_.Vm.Name’. Therefore, if you are interested how much memory or CPU VM is configured with,
Select UserName, CreatedTime, FullFormattedMessage, @{ Name="VM"; Expression={$_.Vm.Name}}, @{ Name="CPU"; Expression={(Get-VM -Name $_.Vm.Name).NumCPU}}
Full list of virtual machine events:
VMware vSphere API 5.1:
http://pubs.vmware.com/vsphere-51/index.jsp#com.vmware.wssdk.apiref.doc/vim.event.VmEvent.html
- CustomizationEvent, DrsRuleComplianceEvent, DrsRuleViolationEvent, MigrationEvent, NoMaintenanceModeDrsRecommendationForVM, NotEnoughResourcesToStartVmEvent, VmAcquiredMksTicketEvent, VmAcquiredTicketEvent, VmAutoRenameEvent, VmBeingCreatedEvent, VmBeingDeployedEvent, VmBeingHotMigratedEvent, VmBeingMigratedEvent, VmCloneEvent, VmConfigMissingEvent, VmConnectedEvent, VmCreatedEvent, VmDasBeingResetEvent, VmDasResetFailedEvent, VmDasUpdateErrorEvent, VmDasUpdateOkEvent, VmDateRolledBackEvent, VmDeployedEvent, VmDeployFailedEvent, VmDisconnectedEvent, VmDiscoveredEvent, VmDiskFailedEvent, VmEmigratingEvent, VmEndRecordingEvent, VmEndReplayingEvent, VmFailedMigrateEvent, VmFailedRelayoutEvent, VmFailedRelayoutOnVmfs2DatastoreEvent, VmFailedStartingSecondaryEvent, VmFailedToPowerOffEvent, VmFailedToPowerOnEvent, VmFailedToRebootGuestEvent, VmFailedToResetEvent, VmFailedToShutdownGuestEvent, VmFailedToStandbyGuestEvent, VmFailedToSuspendEvent, VmFailedUpdatingSecondaryConfig, VmFailoverFailed, VmFaultToleranceStateChangedEvent, VmFaultToleranceTurnedOffEvent, VmFaultToleranceVmTerminatedEvent, VmGuestRebootEvent, VmGuestShutdownEvent, VmGuestStandbyEvent, VmInstanceUuidAssignedEvent, VmInstanceUuidChangedEvent, VmInstanceUuidConflictEvent, VmMacAssignedEvent, VmMacChangedEvent, VmMacConflictEvent, VmMaxFTRestartCountReached, VmMaxRestartCountReached, VmMessageErrorEvent, VmMessageEvent, VmMessageWarningEvent, VmMigratedEvent, VmNoCompatibleHostForSecondaryEvent, VmNoNetworkAccessEvent, VmOrphanedEvent, VmPoweredOffEvent, VmPoweredOnEvent, VmPoweringOnWithCustomizedDVPortEvent, VmPrimaryFailoverEvent, VmReconfiguredEvent, VmRegisteredEvent, VmRelayoutSuccessfulEvent, VmRelayoutUpToDateEvent, VmReloadFromPathEvent, VmReloadFromPathFailedEvent, VmRelocateSpecEvent, VmRemoteConsoleConnectedEvent, VmRemoteConsoleDisconnectedEvent, VmRemovedEvent, VmRenamedEvent, VmRequirementsExceedCurrentEVCModeEvent, VmResettingEvent, VmResourcePoolMovedEvent, VmResourceReallocatedEvent, VmResumingEvent, VmSecondaryAddedEvent, VmSecondaryDisabledBySystemEvent, VmSecondaryDisabledEvent, VmSecondaryEnabledEvent, VmSecondaryStartedEvent, VmStartingEvent, VmStartingSecondaryEvent, VmStartRecordingEvent, VmStartReplayingEvent, VmStaticMacConflictEvent, VmStoppingEvent, VmSuspendedEvent, VmSuspendingEvent, VmTimedoutStartingSecondaryEvent, VmUpgradeCompleteEvent, VmUpgradeFailedEvent, VmUpgradingEvent, VmUuidAssignedEvent, VmUuidChangedEvent, VmUuidConflictEvent, VmWwnAssignedEvent, VmWwnChangedEvent, VmWwnConflictEvent
VMware Infrastructure API 2.5:
http://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.event.VmEvent.html
- CustomizationEvent, MigrationEvent, NoMaintenanceModeDrsRecommendationForVM, NotEnoughResourcesToStartVmEvent, VmAcquiredMksTicketEvent, VmAutoRenameEvent, VmBeingCreatedEvent, VmBeingDeployedEvent, VmBeingHotMigratedEvent, VmBeingMigratedEvent, VmCloneEvent, VmConfigMissingEvent, VmConnectedEvent, VmCreatedEvent, VmDasUpdateErrorEvent, VmDasUpdateOkEvent, VmDateRolledBackEvent, VmDeployedEvent, VmDeployFailedEvent, VmDisconnectedEvent, VmDiscoveredEvent, VmDiskFailedEvent, VmEmigratingEvent, VmFailedMigrateEvent, VmFailedRelayoutEvent, VmFailedRelayoutOnVmfs2DatastoreEvent, VmFailedToPowerOffEvent, VmFailedToPowerOnEvent, VmFailedToRebootGuestEvent, VmFailedToResetEvent, VmFailedToShutdownGuestEvent, VmFailedToStandbyGuestEvent, VmFailedToSuspendEvent, VmFailoverFailed, VmGuestRebootEvent, VmGuestShutdownEvent, VmGuestStandbyEvent, VmMacAssignedEvent, VmMacChangedEvent, VmMacConflictEvent, VmMessageEvent, VmMigratedEvent, VmNoNetworkAccessEvent, VmOrphanedEvent, VmPoweredOffEvent, VmPoweredOnEvent, VmReconfiguredEvent, VmRegisteredEvent, VmRelayoutSuccessfulEvent, VmRelayoutUpToDateEvent, VmRelocateSpecEvent, VmRemovedEvent, VmRenamedEvent, VmResettingEvent, VmResourcePoolMovedEvent, VmResourceReallocatedEvent, VmResumingEvent, VmStartingEvent, VmStaticMacConflictEvent, VmStoppingEvent, VmSuspendedEvent, VmSuspendingEvent, VmUpgradeCompleteEvent, VmUpgradeFailedEvent, VmUpgradingEvent, VmUuidAssignedEvent, VmUuidChangedEvent, VmUuidConflictEvent, VmWwnAssignedEvent, VmWwnChangedEvent, VmWwnConflictEvent
How do i send the output to a xls here ? which all other colums I can add in here ? I need CPU/Memory/Disk for them
Hi Dan,
The trick is to get VM name for the event we get from Get-VIEvent… You can do so as ‘$_.Vm.Name’
Select UserName, CreatedTime, FullFormattedMessage, @{ Name=”VM”; Expression={$_.Vm.Name}}, @{ Name=”CPU”; Expression={(Get-VM -Name $_.Vm.Name).NumCPU}} – VM name and CPU
Use the same logic to add any virtual machine properties (Get-VM | Get-Member).
If you want to export to an Excel file, you can export to CSV file – Export-Csv -Path “c:vms.csv”
Hope this helps.
Thanks Mark !
I ran the script, i found that some of the vms are not showing memory/cpu values, the reason was they were deleted post created or renamed.
SO how can we handle this case ? I would like the script to report the VMs deleted ( so justification why CPU/ram/Disk showing zero) & renamed (give the CPU/ram/Disk info )
My script is which needs modification is
Get-VM -Location CA | Get-VIEvent -Start (Get-Date).adddays(-30) | `
where {$_.gettype().Name -eq “VmCreatedEvent”} | `
select @{N=”VMname”; E={$_.Vm.Name}},
@{N=”CreatedTime”; E={$_.CreatedTime}},
@{N=”Host”; E={$_.Host.Name}},
@{N=”User”; E={$_.UserName}},
@{N=”vCPU”; E={(Get-VM $_.Vm.Name).numcpu }},
@{N=”MemoryGB”; E={(Get-VM $_.Vm.Name).MemoryGB}},
@{N=”ProvisionedSpaceGB”; E={[Math]::Round((Get-VM $_.Vm.Name).ProvisionedSpaceGB)}},
@{N=”UsedSpaceGB”; E={[Math]::Round((Get-VM $_.Vm.Name).UsedSpaceGB)}} | Export-Csv c:Export-CA-vminfo.csv -NoTypeInformation
Can you advice for the fix ..
I ran some tests and yes, you are correct, if you rename VM, the script will not work correctly as the vCenter still holds the old VM name in the events database.
OldName : DeleteME
NewName : DontDeleteME
The problem is that the script queries event database and finds the EVENT when VM was created. You need to amend the script to query the new (current) VM name to get the specs.
Dan,
I may have cracked it! To avoid the confusion with the names, you can refer to VM’s ID rather than the name!
(Get-VM -Id $_.Vm.Vm).MemoryGB etc etc
Dan,
One more thing to try to speed up the script:
“Get-VIEvent -Start (Get-Date).adddays(-30)”
You can also play with the number of events you need to query, i.e. -MaxSamples 10 (default 100). Double check how many events are logged in your environment during VM creation.
Thanks Mark.. I will give it a try
I need Status of the events.. one more thing does Get-VIEvent pull events and task (VM) or only the events. What I am looking for is successfull or failed snapshot creation and deletion tasksevents at a VM
Hi Vivek,
You may look iton this blog post: http://www.vstrong.info/2013/08/20/who-created-these-vm-snapshots/
Hey Mark – how would I add to this script to pull last guest logon?
Hey,
You will need to query System Events from within the Guest OS.
Thanks Man – very appreciated :-)
Hi All,
Any script to get the deleted VM details.