Tech Blog‎ > ‎

PowerShell - Convert Array To HashTable

posted Aug 2, 2012, 6:26 AM by Victor Zakharov   [ updated Aug 2, 2012, 6:26 AM ]
There are many ways to do this, depending on what you need. In this article I'm going to highlight 2 of them.

1. Function-style conversion:

function ArrayToHash($a)
{
    $hash = @{}
    $a | foreach { $hash[$_.ProcessName] = $_ }
    return $hash
}

Usage:

ArrayToHash (Get-Process)

2. Filter-style conversion:

filter ArrayToHash
{
    begin { $hash = @{} }
    process { $hash[$_.ProcessName] = $_ }
    end { return $hash }
}

Usage:

Get-Process | ArrayToHash

Comments