PowerShell 将字典转换为哈希表

Shu*_*bao 6 powershell hash dictionary hashtable

我有一个在 Azure 上运行的 Runbook。我得到数据类型System.Collections.Generic.Dictionary`2[System.String,System.String],但我需要将其转换为System.Collections.Hashtable

我找到了一个使用 C# 的示例,但如何使用 Power Shell 来实现呢?

换句话说,在我的场景中,我需要将字典类型转换为哈希表。

mkl*_*nt0 9

为了用更符合 PowerShell 惯用的解决方案来补充Kory Gill 的有用答案:

  • PowerShell 的类型加速器[System.Collections.Hashtable][hashtable]

  • 如果强制转换类型具有 RHS 类型或其实现的接口的单参数构造函数,则PowerShell 允许您使用强制转换语法。

因此,在这种情况下,您可以直接投射到[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
Run Code Online (Sandbox Code Playgroud)

请注意,嵌套通用字典不会被转换。也就是说,输入字典的将按原样保留,即使它们碰巧也是通用字典。


[1] 通用字典实现IDictionary接口(除其他外),并[hashtable]具有public Hashtable (System.Collections.IDictionary d)构造函数


Kor*_*ill 3

PowerShell 中的 C# 答案很简单:

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
Run Code Online (Sandbox Code Playgroud)