Q. What is a hashtable in PowerShell?
Also called a dictionary or associative array, a hashtable is simply a set of key/value pairs. If you know a key, you can look up its value. It's similar to using a dictionary—if you know a word (the key), you can look up its definition (the value).
August 16, 2010
Q. What is a hashtable in PowerShell?
A. Also called a dictionary or associative array, a hashtable is simply a set of key/value pairs. If you know a key, you can look up its value. It's similar to using a dictionary—if you know a word (the key), you can look up its definition (the value).
To create a hashtable, you use the array operator, @, along with curly braces { }. Separate key/value pairs with a semicolon (;). Try running these lines in the shell:
$hash = @{'one'='don';'two'='greg'}$hash.don$hash.greg$hash
Perhaps the most common use of a hashtable is with the Select-Object and Format-Table cmdlets, where they can be used to create custom columns in your output. Those cmdlets look for keys named "Name" ("Label" is an alternate; you can also use "n" or "l") and "Expression" (or "e"):
Get-WmiObject -class Win32_LogicalDisk |Format-Table DeviceID,@{n="Size(GB)";e={$_.Size / 1GB -as [int]}}
Do you have a Windows PowerShell question? Find more PowerShell FAQs, articles, and other resources at windowsitpro.com/go/DonJonesPowerShell.
About the Author
You May Also Like