PowerShell for Windows Admins

May 31 2015   10:29AM GMT

Multiple expands

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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

1  Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.
  • SADKIN

    There is another way to remove the truncation using just a single command before using powershell to get yor properties.

    # Show the current value for format enumeration

    $FormatEnumerationLimit

    # Set the value for format enumeration to -1

    $FormatEnumerationLimit=-1

    Now if you run a command to retrieve some normally truncated output it will not be truncated.

    # Example

    Get-ADUser john -Properties * | fl memberof, dSCorePropagationData


    Steve

    0 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: