Search code examples
powershellcsvpowercli

How to retrieve more than 1 annotation to CSV


I'm trying to create a report using Get-annotations to retrieve some custom values and actually it works fine, but I only can insert 1 value on report on same line, here below is what I do for 1 value only, is there some syntax to use not like this Get-Annotation -Name value1, value2, value3

$AW= foreach ($vmsowner in $VMsOwners)
{
    $VMlisted = $vmsowner.objectname
    get-vm $VMlisted | Get-Annotation -Name  "Application Owner"| select @{label="VM";expression={$_.AnnotatedEntity}}, @{label="Application Owner";expression={$_.Value}}
}
$AW | ConvertTo-Csv -NoTypeInformation | Out-File  -FilePath $FilenameOwners

Solution

  • Call Get-Annotation inside the calculated property expression(s):

    Get-VM |Select @{Name='VM';Expression={$_}},@{Name='Application Owner';Expression={($_ |Get-Annotation -Name 'Application Owner').Value}},,@{Name='Some other tag';Expression={($_ |Get-Annotation -Name 'Some other tag').Value}}
    

    It might quickly become unreadable with all those calculated property definitions, but you could generate them from a list of annotation names:

    # define annotations your want to retrieve per vm
    $annotations = 'Application Owner', 'Data Owner', 'Some other tag', 'Something else completely'
    
    # generate calculated property definitions
    $properties = @(
        @{Name='VM';Expression={$_}}
        $annotations |ForEach-Object {
            $annotationName = $_
            @{Name=$_;Expression=[scriptblock]::Create("`$(`$_ | Get-Annotation -Name '$_').Value")}
        }
    )
    
    # fetch VMs and select properties
    Get-VM |Select $properties