我有一个在 Azure 上运行的 Runbook。我得到一个数据类型 System.Collections.Generic.Dictionary`2[System.String,System.String] ,但我需要将其转换为 System.Collections.Hashtable .
我找到了 example使用 C#,但是如何使用 Power Shell 来做到这一点?
换句话说,在我的场景中,我需要将字典类型转换为哈希表。
最佳答案
补充Kory Gill's helpful answer使用更 PowerShell 惯用的解决方案:
[System.Collections.Hashtable]
的 PowerShell 类型加速器是 [hashtable]
因此,您可以直接投给
[hashtable]
在这种情况下。 [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
请注意,嵌套的通用字典不会被转换。也就是说,输入字典的值保持原样,即使它们恰好也是通用字典。[1] 通用字典实现
IDictionary
接口(interface)(以及其他)和[hashtable]
有一个 public Hashtable (System.Collections.IDictionary d)
constructor
关于PowerShell 将字典转换为哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48679157/