Automation

 View Only
  • 1.  Get-Annotation and export to csv

    Posted Oct 01, 2012 03:53 PM

    I am trying to export the custom Annotation fields to a csv file with foreach and having trouble get it to work where I want.

    1.     Is it possiible to export them with foreach or do I have to use foreach-object?

    $vms = get-vm pt*
    foreach ($vm in $vms){
        $vm = Get-View $vm.ID
        $nm = $vm.name
        $hn = $vm.guest.hostname
        $ip = $vm.guest.ipaddress
        $contact = get-vm $vms | Get-Annotation -CustomAttribute "System Contact"|select Value
        $vm | select `
        @{Name = "Name"; E={$nm}},`
        @{Name = "Contact"; E={$contact}},`
        @{Name = "Hostname"; E={$hn}},`
        @{Name = "IP"; E={$ip}}
    }format-table -AutoSize -Wrap

    2.     How can I get rid of the "{@{Value=" in the output??

    Name                          Contact                       Hostname                      IP
    ----                          -------                       --------                      --
    PT1                      {@{Value=abcd.Serverteam...     pt1.abcd.com              10.0.1.5
    PT2                      {@{Value=abcd.Serverteam...     pt2.abcd.com              10.0.1.33


  • 2.  RE: Get-Annotation and export to csv

    Posted Oct 01, 2012 04:00 PM

    The problem is that foreach is a statement, not a cmdlet.

    So you need a little trick to put the objects coming from the Select cmdlet in the pipeline.

    $vms = get-vm pt*
    &{foreach ($vm in $vms){
        $vm = Get-View $vm.ID
        $nm = $vm.name
        $hn = $vm.guest.hostname
        $ip = $vm.guest.ipaddress
        $contact = get-vm $vms | Get-Annotation -CustomAttribute "System Contact"|
        Select Value $vm | select `
        @{Name = "Name"; E={$nm}},
        @{Name = "Contact"; E={$contact}},
        @{Name = "Hostname"; E={$hn}},
        @{Name = "IP"; E={$ip}}
    }} | Export-Csv c:\report.csv -NoTypeInformation -UseCulture

    And concerning your question about foreach and ForEach-Object, Brandon did a good post on that subject.

    See hist Why use foreach vs foreach-object.



  • 3.  RE: Get-Annotation and export to csv

    Posted Oct 01, 2012 04:17 PM

    I see. The export works but the annotation is fielding is missing. Any clue?



  • 4.  RE: Get-Annotation and export to csv
    Best Answer

    Posted Oct 01, 2012 05:43 PM

    The better, more PowerShell, way of doing this would be to use the pipeline.

    Something like this

    Get-VM tp* | Select Name,
      @{N="Hostname";E={$_.Guest.Hostname}},
     
    @{N="IP address";E={$_.Guest.IpAddress}},
      @{N="Contact";E={     Get-Annotation -Entity $_ -CustomAttribute "System Contact" |     Select -ExpandProperty Value}} |
    Export-Csv
    c:\report.csv -NoTypeInformation -UseCulture


  • 5.  RE: Get-Annotation and export to csv

    Posted Oct 27, 2012 03:14 PM

    tyvm.