I have a weekly snapshot report run that uses the following script:
$snaps = @()
$currsnaps = get-vm | Get-Snapshot | Select VM, Name, Created, SizeGB
$css = "<style>BODY{font-family: Arial; font-size: 10pt;}
TABLE{border: 1px solid black; border-collapse: collapse;}
TH{border: 1px solid black; background: #dddddd; padding: 5px;}
TD{border: 1px solid black; padding: 5px;}</style>
"
foreach ($snap in $currsnaps){
$user = ($snap.VM | Get-ViEvent | ?{$_.CreatedTime -match $snap.Created} | ?{$_.FullFormattedMessage -match "snapshot"}).Username
If ($snap.Name -ne "__GX_BACKUP__"){
$builder = New-Object System.Object
$builder | Add-Member -Type NoteProperty -Name VM -Value $snap.VM
$builder | Add-Member -Type NoteProperty -Name SnapName -Value $snap.Name
$builder | Add-Member -Type NoteProperty -Name TimeStamp -Value $snap.Created
$builder | Add-Member -Type NoteProperty -Name SizeGB -Value $([math]::floor($snap.SizeGB))
$snaps += $builder
}
}
I've tried adding the following code to include the user that created the snapshot.
$builder | Add-Member -Type NoteProperty -Name CreatedBy -Value $user.UserName
$builder | Add-Member -Type NoteProperty -Name CreatedBy -Value $user
I've also added .AddSeconds(-5) to the $snap.Created, along with .AddMinutes(5). When I add -MaxSamples 5 the script errors stating a parameter cannot be found that matches MaxSamples.
When I try to add the above code the user name does not show up in the final report.
However, when I run this script, the output displays the domain\username every time.
foreach ($snap in Get-VM | Get-Snapshot)
{$snapevent = Get-VIEvent -Entity $snap.VM -Types Info -Finish $snap.Created -MaxSamples 1 | Where-Object {$_.FullFormattedMessage -imatch 'Task: Create virtual machine snapshot'}
if ($snapevent -ne $null){Write-Host ( "VM: "+ $snap.VM + ". Snapshot '" + $snap + "' created on " + $snap.Created.DateTime + " by " + $snapevent.UserName +".")}
else {Write-Host ("VM: "+ $snap.VM + ". Snapshot '" + $snap + "' created on " + $snap.Created.DateTime + ". This event is not in vCenter events database")}}
How can I integrate the code that works from the 2nd script into the 1st script?