PowerShell - Convert Array To HashTable

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