Well I solved my own problem. Go me. The issue is timing. The snapshots that were failing were snapshots taking a long time to complete. The solution is to change the Finish time to add a couple minutes to it.
Old code:
$snapevent = Get-VIEvent -Entity $snapshot.VM -Types Info -Finish $snapshot.Created -MaxSamples 1
New code:
$snapevent = Get-VIEvent -Entity $snapshot.VM -Types Info -Finish $snapshot.Created.AddMinutes(5) -MaxSamples 1
This gives it a little wiggle room to find the event. 2 mins catches most things for me but 5 mins seems the most reliable.
Original Message:
Sent: Sep 30, 2024 09:08 AM
From: Todd Bertschi
Subject: Syncing up snapshot to user who created it
I'm having an issue with some code. I run a weekly report to pull all snapshots created in a given time frame so I can go back and berate the user who has not cleaned up after themselves. It's a fairly standard bit of code. Pull all the VMs, get the cluster name and then snapshots if they have one. After that, I'm searching the events for when the snapshot is created and pulling the name. I'm not using LucD's Get-VIEventPlus code in this report but I have plans to eventually switch it over to make my code more uniform. This should be an easy search though and my problem is I keep getting a few results about not being able to find the event. If I run the code manually against a problem VM, I do get the result I need. Does anyone have any idea why I'm not getting consistent results before I start re-writing it?
<code>
# Get all VMs
$VMs = Get-VM
# Create empty array to hold snapshot information
$SnapshotInfo = @()
# Loop through each VM and get snapshot information
foreach ($VM in $VMs) {
$cluster = Get-VM $VM | select @{N="ClusterName"; E={($_ | Get-Cluster).Name}}
$Snapshots = Get-Snapshot -VM $VM
# Loop through each snapshot and add information to array
foreach ($Snapshot in $Snapshots) {
## Getting owner via Events
$snapevent = Get-VIEvent -Entity $snapshot.VM -Types Info -Finish $snapshot.Created -MaxSamples 1 | Where-Object {$_.FullFormattedMessage -imatch 'Task: Create virtual machine snapshot'}
if ($snapevent -ne $null){
$snap_owner = $snapevent.UserName}
else {
$snap_owner = "This event is not in vCenter events database"
ErrorLog $snapevent
}
$SnapshotInfo += [PSCustomObject]@{
Cluster = $cluster.ClusterName
VMName = $VM.Name
SnapshotName = $Snapshot.Name
Created = $Snapshot.Created
Description = $Snapshot.Description
SizeGB = [math]::Round(($Snapshot.SizeGB),2)
PowerState = $VM.Powerstate
Owner = $snap_owner
}
}
}
</code>