willster07
Contributor
Contributor

Looping in User name to custom attribute Creator

Jump to solution

PowerCLI script VM creation date and user info - VMware Technology Network VMTN - PowerCLI-script-VM-creation-date-and-user-info/td-p/1843709

@LucD This report is fantastic.

Is there a way since this exists: User = $_.UserName

To have it populate a custom attribute we've been adding manually for the User who created the VM?

Realizing of course that user info purges from the logs, but going forward it would help out in a big way.  

 

Thanks in advance.

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership

You mean something like this?
I changed the original script to avoid having to do multiple costly Get-VIEvent calls.

$caName = 'BuildDate'
try {
    $ca = Get-CustomAttribute -Name $caName -ErrorAction Stop
} catch {
    $ca = New-CustomAttribute -Name $caName -TargetType VirtualMachine
}


$vmName = '*'
$eventTYpes = 'VmCreatedEvent', 'VmClonedEvent', 'VmDeployedEvent', 'VmRegisteredEvent'

$vms = Get-VM -Name $vmName

Get-VIEvent -Entity $vms -MaxSamples ([int]::MaxValue) |
where { $eventTypes -contains $_.GetType().Name } |
Group-Object -Property { $_.VM.Name } |
ForEach-Object -Process {
    $event = $_.Group |
        Sort-Object -Property CreatedTime -Descending |
        select -First 1 
    
    Set-Annotation -Entity $_.Name -CustomAttribute $ca -Value $event.UserName
}
   


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

2 Replies
LucD
Leadership
Leadership

You mean something like this?
I changed the original script to avoid having to do multiple costly Get-VIEvent calls.

$caName = 'BuildDate'
try {
    $ca = Get-CustomAttribute -Name $caName -ErrorAction Stop
} catch {
    $ca = New-CustomAttribute -Name $caName -TargetType VirtualMachine
}


$vmName = '*'
$eventTYpes = 'VmCreatedEvent', 'VmClonedEvent', 'VmDeployedEvent', 'VmRegisteredEvent'

$vms = Get-VM -Name $vmName

Get-VIEvent -Entity $vms -MaxSamples ([int]::MaxValue) |
where { $eventTypes -contains $_.GetType().Name } |
Group-Object -Property { $_.VM.Name } |
ForEach-Object -Process {
    $event = $_.Group |
        Sort-Object -Property CreatedTime -Descending |
        select -First 1 
    
    Set-Annotation -Entity $_.Name -CustomAttribute $ca -Value $event.UserName
}
   


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

willster07
Contributor
Contributor

Just getting to this.  Threw me at first, you used the script you did for the other custom attribute BuildDate.  

Changed that first variable to DeployedBy and it worked flawlessly.  Thanks again!  Very much appreciated.

0 Kudos