PowerShell将字典转换为哈希表

PowerShell将字典转换为哈希表,powershell,dictionary,hash,hashtable,Powershell,Dictionary,Hash,Hashtable,我有一本运行在Azure上的runbook。我得到一个数据类型System.Collections.Generic.Dictionary`2[System.String,System.String],但我需要将其转换为System.Collections.Hashtable 我发现了一个使用C#的方法,但是如何使用powershell呢 换句话说,在我的场景中,我需要将字典类型转换为哈希表。PowerShell中的C#答案很简单: Write-Host "....dictionary" $d =

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

我发现了一个使用C#的方法,但是如何使用powershell呢

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

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
要使用更具PowerShell风格的解决方案进行补充,请执行以下操作:

  • PowerShell用于
    [System.Collections.Hashtable]
    的类型加速器是
    [Hashtable]

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

因此,在这种情况下,您可以直接强制转换到
[hashtable]
。[1]

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



[1] 通用词典实现了
IDictionary
接口(以及其他接口),并且
[hashtable]
具有一个可以通过预定义变量类型将词典强制转换为hashtable

[hastable]$var = $var

@Vivere,请查看更新的答案。
[hastable]$var = $var