Friday 14 July 2017

Using Powershell values from the start of the pipeline in a table at the end.

There are two ways to deal with large arrays of nested objects in powershell.

One is a bunch of nested foreach loops which is nicely readable in scripts.

However the beauty of the pipeline is that you can run output from one command into the input for another, which is often the way to drill down into dependent objects.

One such example is Vmware portgroups in Powercli.

The hierachy can be several levels deep

e.g.

cluster
 -> host
   -> vswitch
      -> portgroup

I wanted to build a table showing portgroups on all hosts in a cluster, ignoring the default management kernel port

The command is quite simple.

Get-Cluster -name Cluster01 | Get-VMHost | Get-VirtualSwitch -name vSwitch0 | Get-VirtualPortGroup | where {$_.name -ne "Management Network" | select Name, VirtualSwitch | ft -autosize

This produces a nice table showing the portgourp name and the vswitch it's connected to.

However the hostname isn't a property of the portgroup, it's a property of the vswitch (or the host) so the question is how to show it in the table.

The answer is with the pipelinevariable command (introduced in PS4 and above) and a custom property expression.

Get-Cluster -name Cluster01 Get-VMHost | Get-VirtualSwitch -name vSwitch0 -PipelineVariable 'fi' | Get-VirtualPortGroup | where {$_.name -ne "Management Network"} | select Name, VirtualSwitch, @{Name = "VMHost";Expression = {($fi.vmhost)}} | ft -AutoSize

This returns a nice table of three columns, with the third column

No comments: