HOWTO: Perform lookup conversions in PowerShell

This HOWTO describes how to use PowerShell to solve for a situation where you have a series of values and you want to have them display a different set of values.  Think of a scenario where you get an array that contains country codes such as "CA, US, JP" but you want them to display as "Canada, United States, Japan".  Here is how you can do that.  Special thanks to Ed Wilson, aka the scripting guy as this was a recent post of his:
http://blogs.technet.com/b/heyscriptingguy/archive/2014/09/10/inventory-drive-types-by-using-powershell.aspx

Consider the scenario where you want to list the types of disks on a system.  You find this command:

Get-CimInstance Win32_LogicalDisk | Select DeviceID, DriveType | ft -AutoSize

The output of which looks like:

DeviceID DriveType
——– ———
C:               3
D:               3
E:               2

That’s fantastic.  But what does 2 and 3 mean?  You check the MSDN documentation and you find a list of what the numbers mean.  Now create a key/value pair hash table where the left hand side is the value that will be returned by your object and the right hand value is what you actually want displayed:

$hash = @{
   2 = "Removable disk"
   3="Fixed local disk"
   4="Network disk"
   5 = "Compact disk"}

Next, use the same command above but this time for DriveType, use a Name/Expression to apply some additional code to it before displaying whereby you will take the value it returns and grab the matching value from the hash table

Get-CimInstance Win32_LogicalDisk | Select DeviceID, @{LABEL=’TypeDrive’; EXPRESSION={$hash.item([int]$_.DriveType)}}

In other words, the Get-CimInstance command is returning a "3" for Drive Type but before displaying to the screen, the 3 is passed to the hash table and returned to display as "Fixed local disk".

DeviceID TypeDrive      
——– ———      
C:       Fixed local disk
D:       Fixed local disk
E:       Removable Disk

Very cool!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.