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

Posts