Skip to content

Instantly share code, notes, and snippets.

@WimObiwan
Created August 26, 2019 14:38
Show Gist options
  • Save WimObiwan/c655652f9683c0ded8ae0e986d39cc3b to your computer and use it in GitHub Desktop.
Save WimObiwan/c655652f9683c0ded8ae0e986d39cc3b to your computer and use it in GitHub Desktop.
ConvertTo-Dictionary
function ConvertTo-Dictionary {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
$Collection,
[Parameter(Mandatory=$true)]
[string]$Key
)
begin {
$dict = $null
}
process {
foreach ($item in $Collection) {
$keyVal = $item."$Key"
if (-not $dict) {
$keyType = $keyVal.GetType().FullName
$valueType = $item.GetType().FullName
$dictionaryType = "System.Collections.Generic.Dictionary[$keyType, $valueType]"
Write-Verbose "Creating new dictionary of type $dictionaryType"
$dict = New-Object $dictionaryType
}
$dict.Add($keyval, $item)
}
}
end {
$dict
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment