首页 > 解决方案 > 如何在powershell中打印将一个值作为输入的对象的内容?

问题描述

我需要通过以 id 作为输入来显示与每个 id 号相关的内容。原始格式为json,如下:

{
    "ids": [
        {
            "id": "121100",
            "Libraries": [
                "cpa_sample_code_s.so",
                "stv_test_code_s.so"
            ],
            "Commands": [
                "qaeMemInit",
                "icp_sal_userStartMultiProcess(\"SSL\",CPA_FALSE)",
                "rsaPerformanceTest(1,0x02,2,10,1000) [RSA API]"
            ],
            "Label": "rsaPerformanceTest-Test"
        },
        {
            "id": "121103",
            "Libraries": [
                "cpa_sample_code_s.so",
                "stv_test_code_s.so"
            ],
            "Commands": [
                "qaeMemInit",
                "icp_sal_userStartMultiProcess(\"SSL\",CPA_FALSE)",
                "dhPerformanceTest(1,0x02,10,10000)"
            ],
            "Label": "dhPerformanceTest-Test"
        },
        {
            "id": "121202",
            "Libraries": [
                "cpa_sample_code_s.so",
                "stv_test_code_s.so"
            ],
            "Commands": [
                "qaeMemInit",
                "icp_sal_userStartMultiProcess(\"SSL\",CPA_FALSE)",
                "runDcTestPerf(3,0,2,1,1,1,65536,1,100)"
            ],
            "Label": "runDcTestPerf-Test"
        }
    ]
}

我将上述格式从 json 文件转换为下面提到的$myVar. 我的变量有一个哈希表,但我无法使用$myvar["id"]. 我对powershell很陌生。有人可以帮忙吗?

$myFile = get-content C:\Users\ssc\Desktop\powershell\activity.json
$myvar = $myFile | ConvertFrom-Json
PS C:\Windows\system32> $myvar
ids                                                                                                                                                                                                                                                                                             
---                                                                                                                                                                                                                                                                                             
{@{id=121100; Libraries=System.Object[]; Commands=System.Object[]; Label=rsaPerformanceTest-Test}, @{id=121103; Libraries=System.Object[]; Commands=System.Object[]; Label=dhPerformanceTest-Test}, @{id=121202; Libraries=System.Object[]; Commands=System.Object[]; Label=runDcTestPerf-Test}}
PS C:\Windows\system32> 

标签: powershellfor-loopforeachhashtable

解决方案


$myvar.idsid当前包含一个对象数组 - 但您可以使用属性作为键填充自己的哈希表,如下所示:

$myHashtable = @{}
$myvar.ids |ForEach-Object { $myHashtable[$_.id] = $_ }

此时您应该能够通过 id 解决每个问题:

PS ~> $myHashtable["121100"]

id     Libraries                                  Commands
--     ---------                                  --------
121100 {cpa_sample_code_s.so, stv_test_code_s.so} {qaeMemInit, icp_sal_userStartMultiProcess("SSL",CPA_FALSE), ...}

推荐阅读