In the previous tip we explained how you can use a hash table to show simple selection dialogs, yet when the user selects an item, return full rich objects.

A hash table can basically use anything as a key. In the previous example, we used a string. It could as well be another object. This really leads you to a highly flexible approach for selection dialogs.

Simply use Select-Object to select those properties that you’d like to show in a grid view window, and use this as key to your hash table.

# create a hash table where the key is the selected properties to display, 
# and the value is the original object
$hashTable = Get-WmiObject -Class Win32_NetworkAdapterConfiguration |
    # sort the objects by a property of your choice
    Sort-Object -Property Description |
    # use an ordered hash table to keep sort order
    # (requires PowerShell 3; for older PowerShell remove [Ordered])
    ForEach-Object { $ht = [Ordered]@{}}{
        # specify the properties that you would like to show in a grid view window
        $key = $_ | Select-Object -Property Description, IPAddress, MacAddress
        $ht.Add($key, $_)
    }{$ht}
    Group-Object -Property Description, Index -AsHashTable -AsString

# show the keys in the grid view window
$hashTable.Keys |
    Out-GridView -Title "Select Network Card" -OutputMode Single |
    ForEach-Object {
        # and retrieve the original (full) object by using
        # the selected item as key into your hash table
        $selectedObject = $hashTable[$_]
        $selectedObject | Select-Object -Property *
    }

When you run this code, the grid view window shows a list of network adapters and displays only the properties you selected (Description, IPAddress, and MacAddress).

When the user selects an item, the code returns the original (full) object so even though the grid view window displayed a limited object, the full object is still available.

Are you an experienced professional PowerShell user? Then learning from default course work isn’t your thing. Consider learning the tricks of the trade from one another! Meet the most creative and sophisticated fellow PowerShellers, along with Microsoft PowerShell team members and PowerShell inventor Jeffrey Snover. Attend this years’ PowerShell Conference EU, taking place April 17-20 in Hanover, Germany, for the leading edge. 35 international top speakers, 80 sessions, and security workshops are waiting for you, including two exciting evening events. The conference is limited to 300 delegates. More details at www.psconf.eu

Twitter This Tip! ReTweet this Tip!

Anonymous