PowerShell 将字典转换为哈希表

标签 powershell dictionary hash hashtable

我有一个在 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]
  • 如果强制转换的类型具有 RHS 类型或由它实现的接口(interface)的单参数构造函数,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
    
    请注意,嵌套的通用字典不会被转换。也就是说,输入字典的值保持原样,即使它们恰好也是通用字典。

    [1] 通用字典实现 IDictionary接口(interface)(以及其他)和[hashtable]有一个 public Hashtable (System.Collections.IDictionary d) constructor

    关于PowerShell 将字典转换为哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48679157/

    相关文章:

    powershell - 安装包 : Dependency loop detected for package 'Microsoft.Data.Sqlite'

    python - 如何防止 dict.update(new_dict) 添加空数据?

    c# - 使用 RSACryptoServiceProvider 签名的速度

    PHP 问题 : password_hash function is not able to generate a salt

    hash - REST 的 API key

    performance - 有没有办法从大命令中更快地流出数据?

    powershell - 带有哈希表的 Foreach 对象?

    .net - 如何在 PowerShell 中获取数字 HTTP 状态代码

    python - 使用 zip 和列表理解来创建字典

    python - 根据值从现有字典生成所有可能的字典