You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell函数中传递参数查询对象子属性?

解决PowerShell中通过参数传递嵌套属性路径无法访问的问题

你的问题出在PowerShell对属性访问的解析逻辑:当使用$psobject.$select时,PowerShell会把$select的完整值当作单个属性名去查找,而不是解析成roles.categories这样的嵌套属性链,自然找不到对应的属性。

下面提供两种可行的解决方案:

方案1:使用Invoke-Expression解析路径

适合参数来源可信的场景,代码实现简单:

function Get-Sub([string]$select)
{
    $var_string = '{"roles": {"categories": {"test": "111"}}}'
    $psobject = $var_string | ConvertFrom-Json
    $psobject.roles.categories | Out-GridView -Title "Working"
    # 通过Invoke-Expression将字符串路径解析为属性链
    Invoke-Expression "`$psobject.$select" | Out-GridView -Title "Now Working"
}

Get-Sub -select 'roles.categories'

Invoke-Expression会把传入的字符串当作PowerShell代码执行,从而正确识别嵌套的属性访问链。

方案2:拆分路径递归访问(更安全)

如果参数可能来自不可信来源,推荐用这种方法,避免代码注入风险:

function Get-Sub([string]$select)
{
    $var_string = '{"roles": {"categories": {"test": "111"}}}'
    $psobject = $var_string | ConvertFrom-Json
    $psobject.roles.categories | Out-GridView -Title "Working"

    # 将路径按点拆分,逐个遍历访问属性
    $currentObj = $psobject
    foreach ($prop in $select.Split('.')) {
        $currentObj = $currentObj.$prop
    }
    $currentObj | Out-GridView -Title "Now Working"
}

Get-Sub -select 'roles.categories'

这种方法把嵌套路径拆分成单个属性名,循环逐步访问每个层级的属性,既安全又能实现需求。

内容的提问来源于stack exchange,提问作者Paulus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:50:43