Multiple expands

PowerShell outputs objects but sometimes you need just the values. The –Expandproperty parameter of select-object can pull the values from a property.  Compare:

£> Get-VM | select Name

Name
—-
Arista
SphinxLx01
W12R2DSC
W12R2OD01
W12R2SCDC01
W12R2SUS
W12R2TGT
W12R2Web01
W12R2Web02

with

£> Get-VM | select -ExpandProperty Name
Arista
SphinxLx01
W12R2DSC
W12R2OD01
W12R2SCDC01
W12R2SUS
W12R2TGT
W12R2Web01
W12R2Web02

In the first you get an object with just a name property.  In the second you get just the name.

This is good BUT you can only expand a single property in one pipeline. If you need to expand multiple properties you need to do them individually and combine the results into a new object.  For instance to drill down into a 2012 r2 Hyper-V VM and get the IP addresses and the disk size

Get-VM |
foreach {
$props = [ordered]@{
  Name = $($psitem.Name)
  IPAddresses =  $psitem | select -ExpandProperty NetworkAdapters | select -ExpandProperty IPAddresses
  DiskSize = [math]::Round((Get-ChildItem -Path ($psitem | select -ExpandProperty HardDrives | select -ExpandProperty path) | select -ExpandProperty Length) / 1GB, 2)
}
New-Object -TypeName PSObject -Property $props
}

The IP addresses are a simple double expansion.  The disk size you have to expand the harddrives, then the path  – get the file length and re-calculate the size to GB.

NOTE – I know all my VMs only have a single disk. If you have multiple disks you’ll need to build a loop to get all the sizes

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s