Pulling Username from vmware.vim Events

This post was originally published on this site

Hi All,


I have a Script that Reports on Machines Created within the last 24 hours and adds these to a CSV File to be sent out depending on the Regex Value,

I’m currently Adding the Username to the File but only half of the Virtual Machines are getting the UserName Field populated.


$events = Get-VIEvent -Types Info -Start $start -Finish $now -MaxSamples ([int]::MaxValue) -Server $srv 
$deployments = $events | where {$_ -is [Vmware.vim.VmBeingClonedEvent] -or $_ -is [Vmware.vim.VmCreatedEvent]}

foreach($deployment in $deployments){
$dataObj = "" | Select-Object events
$dataObj.events = $events | Where-Object {$_.ChainID -eq $deployment.ChainID}
$deploymentChains += $dataObj

foreach($chain in $deploymentChains) {
$newVM = ($chain.events.vm.name) #Removed $chain.events[*].vm.Name due to position of Event in Some vSphere Environments
$Exists = get-vm -name $newVM -ErrorAction SilentlyContinue

    $deployedvms += $Exists | Where {$deployedvms -notcontains $_} 
    #Do Nothing
foreach($vm in $deployedvms) {
  $cluster = Get-Cluster -VM $vm | Select Name -ExpandProperty Name
  if($cluster -match $regex -or $cluster -match $regex1){
    $userevent = Get-VIEvent -Entity $vm -Start $start -Finish $now -MaxSamples 1 | where {$_ -is [Vmware.vim.VmBeingClonedEvent] -or $_ -is [Vmware.vim.VmCreatedEvent]} | select UserName -ExpandProperty UserName 
        $result = "" | select vmName,ESXname,Powerstate,NumCpu,MemoryGB,ProvisionedSpaceGB
        $result.vmName = $vm.Name
        $result.ESXname = $VM.VMHost
        $result.Powerstate = $vm.Powerstate
        $result.NumCpu = $vm.NumCpu
        $result.MemoryGB = $vm.MemoryGB
$result.ProvisionedSpaceGB = $vm.ProvisionedSpaceGB
  $result | add-member -MemberType NoteProperty -name 'Cluster' -Value $cluster
  $result | add-member -MemberType NoteProperty -name 'vCenter' -Value $item
    $result | add-member -MemberType NoteProperty -name 'UserName' -Value $userevent
  $results += $result  

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.