如何使用对象数组创建自定义哈希表-Powershell / cmd

时间:2019-07-05 16:37:51

标签: arrays powershell object command hashtable

尝试使用get-WmiObject从类中获取许多对象。我必须将其作为哈希表/字典类型返回。

我正在使用的命令:


get-WmiObject -class win32_SoundDevice | select-object Name, Status

我得到的是:

Name                   Status
----                   ------
Intel(R) Display Audio OK
Realtek Audio          OK

我想创建如下所示的内容:

[
    {
        "Name":  "Intel(R) Display Audio",
        "Status":  "OK"
    },
    {
        "Name":  "Realtek Audio",
        "Status":  "OK"
    }
]

我知道我可以将| convertTo-json命令附加到初始命令,但是我想从头开始创建哈希表,因为我将在可能不使用convertTo-json命令的旧式系统上使用它。

2 个答案:

答案 0 :(得分:2)

如果您无法使用ConvertTo-Json cmdlet,这将有所帮助:

function ConvertTo-Json20([object] $item){
    # serializes object(s) to JSON. The result will be in compressed format.
    Add-Type -AssemblyName System.Web.Extensions

    $jsSerializer = New-Object System.Web.Script.Serialization.JavascriptSerializer
    return $jsSerializer.Serialize($item)
}


# When using 'Select-Object Name, Status' you will get an array of PSObjects which the above function 
# cannot handle. Therefore, I'm using Old-School to get the results from the Get-WmiObject cmdlet
# into an array of Hashtables.

$result = Get-WmiObject -Class win32_SoundDevice | ForEach-Object {
    @{
        'Name' = $_.Name
        'Status' = $_.Status
    }
}

ConvertTo-Json20 $result

在我的机器上,结果是

  

[{“名称”:“ Conexant ISST音频”,“状态”:“确定”},{“名称”:“英特尔(R)   显示音频”,“状态”:“确定”}]

答案 1 :(得分:1)

要将序列化PowerShell对象为PowerShell表达式,您可以考虑使用此ConvertTo-Expression cmdlet:

ConvertTo-Expression (get-WmiObject -class win32_SoundDevice | select-object Name, Status)

结果:

[PSCustomObject]@{
        'Name' = 'USB Multi-Channel Audio Device'
        'Status' = 'OK'
},
[PSCustomObject]@{
        'Name' = 'High Definition Audio Device'
        'Status' = 'OK'
},
[PSCustomObject]@{
        'Name' = 'High Definition Audio Device'
        'Status' = 'OK'
}

有关更多信息,请参见:Save hash table in PowerShell object notation (PSON)