We help IT Professionals succeed at work.

Output data from multiple piped cmdlets and format it into table

Blowfelt82 asked
Say I have a number of piped PowerCLI cmdlets:

Get-VM | Get-VMHost | Get-Portgroups

How can I select the columns from each level of the command e.g:

Select Get-VM.Name, Get-VMHost.ID, Get-VMHost.Memory, Get-PortGroups.ID

Note: It is likely that different cmdlets will return identically named columns.

It is also likely that each cmdlet may return multiple lines of data e.g. a VMHost might have multiple VMs associated with it - I want to display this data in a table as follows (I doubt its possible but if columns/rows can use spanning to make the table more presentable even better):

HOST1 | VM1 | PortGroup1
HOST1 | VM1 | PortGroup2
HOST1 | VM1 | PortGroup3
HOST2 | VM2 | PortGroup1
HOST2 | VM2 | PortGroup2
Watch Question

Top Expert 2014
When you need to intercept data in the pipeline so you can use it later on, usually you will use ForEach-Object and capture what you want into variables.  Then you can reference the variables as needed.  You can use Select-Object (could also use New-Object within a loop) with calculated properties to display/output all the information you want.
Get-VM | ForEach `
    $VMname = $_.name
    $_ | Get-VMHost | ForEach `
        $HostID = $_.ID
        $HostMem = $_.Memory
        $_ | Get-Portgroups |
         Select @{n="Host";e={$HostID}},

Open in new window

You can add a pipe at the end to Format-Table (try using the -Autosize and -Wrap parameters to see if that gives you what you want).