从参数中的路径获取PowerShell对象属性

时间:2019-06-28 14:28:20

标签: powershell object

如何配置PowerShell以根据变量的内容选择对象属性(顶级或嵌套)?

我有PowerShell脚本,该脚本读取文件(JSON)的内容,将其转换为对象,然后选择属性之一。但是,内容不一致,并且JSON中所需属性的位置可能会更改。

我希望能够在脚本上设置一个-PropertyPath参数,该参数使用户能够将路径传递到对象内所需的属性。

采用以下示例,该示例允许根据-PropertyPath的值选择对象属性。之所以有效,是因为该属性未嵌套。

$PropertyPath= "myProperty"
$definition = (Get-Content -Path $definitionFilePath -Raw | ConvertFrom-Json).$PropertyPath

现在以下面的失败示例为例,其中要获取的属性是嵌套的(并且确实存在),该失败没有错误,但是$definition为空-可能是因为不存在名为“ random.myProperty”的属性

$PropertyPath= "random.myProperty"
$definition = (Get-Content -Path $definitionFilePath -Raw | ConvertFrom-Json).$PropertyPath

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

点'。'属性代表dereference operator。 Powershell似乎将整个字符串视为属性名称。

获得所需功能的一种方法:使用辅助函数来手动解析和遍历路径(via):

function OutputNested ($obj, $Value )
{
    $value_array = $Value.split(".");    
    $output = $obj;
    foreach ( $nested in $value_array ) 
    {
        $output = $output.$nested;
    }
    return $output;
}

$PropertyPath= "stuff.onetype"
$definitionFilePath = "C:\Users\UserName\Source\powershell\so12943819\so12943819.json"

# Works directly
#$definition = $(Get-Content -Path $definitionFilePath -Raw | ConvertFrom-Json).stuff.onetype

# Works via helper function
$definition = OutputNested (Get-Content -Path $definitionFilePath -Raw | ConvertFrom-Json) $PropertyPath

$definition

JSON输入文件:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

输出:

id name    
-- ----    
 1 John Doe
 2 Don Joeh