Question:
Filtering a Hashtable using GetEnumerator always returns a object[] instead of a Hashtable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Init Hashtable $items = @{ a1 = 1; a2 = 2; b1 = 3; b2 = 4} # apply a filter $filtered = $items.GetEnumerator() | ?{ $_.Key -match "a.*" } # The result looks great $filtered Name Value ---- ----- a2 2 a1 1 # … but it is not a Hashtable :-( $filtered.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array |
Is there a nice solution to this problem?
Thanks a lot for any Help!,
kind regards,
Tom
Answer:
$filtered
is an array of dictionary entries. There’s no single cast or ctor for this as far as I know.
You can construct a hash though:
1 2 3 |
$hash = @{} $filtered | ForEach-Object { $hash.Add($_.Key, $_.Value) } |
Another workflow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Init Hashtable $items = @{ a1 = 1; a2 = 2; b1 = 3; b2 = 4} # Copy keys to an array to avoid enumerating them directly on the hashtable $keys = @($items.Keys) # Remove elements not matching the expected pattern $keys | ForEach-Object { if ($_ -notmatch "a.*") { $items.Remove($_) } } # $items is filtered |