使用 PowerShell 从变量内容中获取值以进行代码解析

Get values from variable contents using PowerShell for code parsing

我已经解析了对变量 $a 的 API 调用的内容。(下面的内容)我只想解析出“依赖项”下的包列表。有没有办法使用 powershell 仅过滤依赖项?

{
"name": "1package",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
    "@babel/runtime": {
        "version": "7",
        "resolved": "https://registry.npmjs.org",
        "integrity": "***",
        "requires": {
            "regenerator-runtime": "^0.13.4"
        }
    },
    "@cloud": {
        "version": "2",
        "resolved": "https://registry.npmjs.org/",
        "integrity": "***"
    },
    "@cloudnative/health-connect": {
        "version": "2",
        "resolved": "https://registry.npmjs.org/@***.tgz",
        "integrity": "***",
        "requires": {
            "@cloudnative/health": "^2.1.1"
        }
    },

所以我只想解析出一个包含

的列表
babel/runtime version 7
cloud version 2
cloudnative/health-connect version 2

通过访问PSObject.Properties of each object we can get the dependency "Name" and the desired values of the properties "Version" and "Resolved". Using a calculated property with Select-Object我们可以构造一个新的对象。

注意,此代码假定您已经在 Json 字符串上使用了 ConvertFrom-Json,并且该对象存储在 $json变量。

$json.dependencies.PSObject.Properties | Select-Object Name,
    @{
        Name = 'Version'
        Expression = { $_.Value.Version }
    }, @{
        Name = 'Resolved'
        Expression = { $_.Value.Resolved }
    }

输出

Name                        Version Resolved
----                        ------- --------
@babel/runtime              7       https://registry.npmjs.org
@cloud                      2       https://registry.npmjs.org/
@cloudnative/health-connect 2       https://registry.npmjs.org/@***.tgz