I have a runbook running on Azure. I get a data type System.Collections.Generic.Dictionary`2[System.String,System.String], but I need convert it to System.Collections.Hashtable.
I find a example using C#, but how can I do it with Power Shell?
In other words, in my scenario, I need convert dictionary type to hashtable.
To complement Kory Gill's helpful answer with a more PowerShell-idiomatic solution:
PowerShell's type accelerator for [System.Collections.Hashtable] is [hashtable]
PowerShell allows you to use cast syntax if the cast's type has a single-argument constructor of the RHS's type or of an interface implemented by it.
Therefore, you can cast directly to [hashtable] in this case.[1]
# Create a sample dictionary (using PSv5+ syntax; in PSv4-, use New-Object)
($dict = [Collections.Generic.Dictionary[string, string]]::new()).Add('foo', 'bar')
# Cast the generic dictionary directly to a hashtable.
# (Assign the result to a variable as needed, e.g.
# $hash = [hastable] $dict
# [hashtable] $hash = $dict # with type constraint (variable type locked in)
# )
[hashtable] $dict
Note that nested generic dictionaries are not converted. That is, the input dictionary's values are retained as-is, even if they happen to be generic dictionaries too.
[1] A generic dictionary implements the IDictionary interface (among others), and [hashtable] has a public Hashtable (System.Collections.IDictionary d) constructor
The C# answer in PowerShell is simply:
Write-Host "....dictionary"
$d = [System.Collections.Generic.Dictionary`2[System.String,System.String]]::new() # `
$d.Add("one", "111")
$d.Add("two", "222")
Write-Host "$d"
$d | ft
Write-Host "....hashtable"
$h = [System.Collections.Hashtable]::new($d)
Write-Host "$h"
$h | ft
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With