如何在powershell中以一个值作为输入打印对象的内容?

How to print the contents of the objects taking one value as input in 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 格式。我的变量有一个散列 table,但我无法使用 $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> 

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

$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), ...}