PowerShell 将字典转换为哈希表
PowerShell convert dictionary to hashtable
我在 Azure 上有一本操作手册 运行。我得到一个数据类型 System.Collections.Generic.Dictionary`2[System.String,System.String],但我需要将其转换为 System.Collections.Hashtable.
我找到了一个使用 C# 的 example,但是如何使用 Power Shell 来实现?
换句话说,在我的场景中,我需要将字典类型转换为哈希表。
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]
PowerShell 允许您使用 cast 语法 如果 cast 类型具有 RHS 类型或由其实现的接口的单参数构造函数。
因此,在这种情况下,您可以 直接转换为 [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
接口(以及其他接口),而 [hashtable]
有一个 public Hashtable (System.Collections.IDictionary d)
constructor
您可以通过预定义变量类型将字典转换为哈希表。
[hastable]$var = $var
我在 Azure 上有一本操作手册 运行。我得到一个数据类型 System.Collections.Generic.Dictionary`2[System.String,System.String],但我需要将其转换为 System.Collections.Hashtable.
我找到了一个使用 C# 的 example,但是如何使用 Power Shell 来实现?
换句话说,在我的场景中,我需要将字典类型转换为哈希表。
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]
PowerShell 允许您使用 cast 语法 如果 cast 类型具有 RHS 类型或由其实现的接口的单参数构造函数。
因此,在这种情况下,您可以 直接转换为 [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
接口(以及其他接口),而 [hashtable]
有一个 public Hashtable (System.Collections.IDictionary d)
constructor
您可以通过预定义变量类型将字典转换为哈希表。
[hastable]$var = $var