首页 > 解决方案 > Powershell PSCustomObject 提取值

问题描述

当创建和使用 PSCustomObjects 导致 NoteProperty 成员具有“定义”(如下所示)时,是否有任何简单的编程方法可以从定义字段中选择值而不诉诸拆分字符串?

例如下面,是否有一种“好”的方法可以从不需要传统字符串操作的名称“token”字段中提取值“silver”?我一直在搞乱 select 和 -ExpandProperty 但没有快速获得任何地方,并且希望朝着正确的方向轻推。

TypeName: System.Management.Automation.PSCustomObject
Name   MemberType   Definition          
----   ----------   ----------          
bsw    NoteProperty decimal bsw=3.14    
name   NoteProperty string name=chris
token  NoteProperty string token=silver 
volume NoteProperty decimal volume=17.22

谢谢。

更新:按照 Thomas 的指导,我想出了这个函数来从 PSObject 中提取 Noteproperty 成员并返回一个带有字段名称和值的 Hashtable:

function convertObjectToHash($psObj) {
    $hashBack = @{}

    try {
        $psObjFieldNames = $psObj | get-member -type NoteProperty | select "Name"
        $psObjFieldNames | foreach-object { 
            $hashBack.Add($_.Name,$psObj.$($_.Name)) }
        }catch{ "Error: $_" }

    return $hashBack
}

谢谢!

标签: powershellpscustomobject

解决方案


您可以像访问任何其他对象一样访问自定义对象的成员:

$myCustomObject.token

再生产:

$myCustomObject = New-Object -TypeName psobject
$myCustomObject | Add-Member -MemberType NoteProperty -Name bsw -Value 3.14
$myCustomObject | Add-Member -MemberType NoteProperty -Name name -Value "chris"
$myCustomObject | Add-Member -MemberType NoteProperty -Name token -Value "silver"
$myCustomObject | Add-Member -MemberType NoteProperty -Name volume -Value 17.22

$myCustomObject | Get-Member -MemberType NoteProperty
$myCustomObject.token

输出:

   TypeName: System.Management.Automation.PSCustomObject

Name   MemberType   Definition                
----   ----------   ----------                
bsw    NoteProperty System.Double bsw=3.14    
name   NoteProperty string name=chris         
token  NoteProperty string token=silver       
volume NoteProperty System.Double volume=17.22

silver

推荐阅读