Hash Tables in PowerShell for Quick Data Management

Posted by:

|

On:

|

Hash tables in PowerShell (also known as Dictionaries) are lists of key-value pairs. They can be used to quickly retrieve or store data.

PowerShell
@{ <key> = <value>; [<key> = <value> ] ...} # unordered table
[ordered]@{ <key> = <value>; [<key> = <value> ] ...} # ordered table

Keep in mind that you can only order a hash table when initializing it. You cannot sort hash table after it’s been created. The alternative is creating an ordered hash table based on the original and somehow parsing the data before passing it over.

Here are some methods you can use to get data from hash tables. You could alternatively use the Select-Object cmdlet to achieve the same result.

PowerShell
$myServers = @{
  WIZWEB01 = "www.wizardshell.com"; WIZSQL01 = "10.1.0.4";  WIZAPP = "10.1.0.4"}
$myServers.keys
$myServers.values
$myServers.WIZWEB01

You can also loop through hash tables. You can loop through keys, values, or both using the Get-Enumerator method.

PowerShell
$myServers.Keys | ForEach-Object {
    "The value of '$_' is: $($myServers[$_])"
}

$myServers.GetEnumerator().ForEach({"The value of '$($_.Key)' is: $($_.Value)"})

You can also add, update, and remove data from a hash table using methods.

PowerShell
$oldServer = "WIZAPP"
$server = "WIZRHL01"
$IPAddress = "10.2.1.5"

$myServers.Add($server, $IPAddress)
$myServers.Remove($oldServer)

There are some interesting things you can do with hash tables since they allow for many datatypes, including another hash table. Nesting allows for

PowerShell
$myProcesses = @{}
$powershell = Get-Process "PowerShell"

$myProcesses.Add("PowerShell", $powershell)

$myServers.Add("Processes", $myProcesses)
$myServers.Processes.PowerShell.id

If you want to convert a large string into key-value pairs, you can do this with the ConvertFrom-StringData cmdlet.

PowerShell
$string = @'
Instruction = Press the "enter" key.
Greeting = Hello, World
'@

ConvertFrom-StringData $string

Final Thoughts on Hash Tables

Many other types of data can be used with hash tables. I have personally used them for tasks like testing external interfaces of devices and recording any script runs that complete with errors. If there are many parameters in a script, you can define each parameter as a key and assign the corresponding value. Afterward, call the cmdlet and use the hash table as an argument. When you get into parallel processing to optimize efficiency, they can keep tasks on multiple threads from interfering with each other or running duplicate processes. All in all, well worth learning and at the very least helps keep yourself from looping through a CSV as a crutch.