function ConvertTo-Dictionary {
  param(
    [ScriptBlock]$KeyExpression,
    [ScriptBlock]$ValueExpression={$_}
  )
  begin { $Result = @{} }
  process { $Result[(&$KeyExpression)]=(&$ValueExpression) }
  end { $Result }
}

I already have this function in a compiled C# PSSnapin that I’ve been using (it’s named differently, which would piss off the PowerShell verb nazi’s) but here is a very short and useful function that you can use to turn any pipeline into a dictionary using an expression for extracting the key and value. Very similar to LINQ’s ToDictionary extension method – not coincidentally.

$Services = Get-Service | ConvertTo-Dictionary {$_.Name} {$_.DisplayName}
$Services['WSearch']
# Windows Search

One Response to “ConvertTo-Dictionary”

Pingbacks (1)
  1. [...] while back I posted about a ConvertTo-Dictionary PowerShell function. This handy little function would take an input object from the pipeline and populate a Hashtable [...]

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>