0
votes

When creating and working with PSCustomObjects which result in a NoteProperty member with a 'Definition' (as shown below), is there any easy, programmatic way to select the values from the definition fields without resorting to splitting the strings?

For example below, is there a 'good' way to extract the value 'silver' from the field of name 'token' that does not requre traditional string manipulations? I've been messing around with select and -ExpandProperty but getting no-where fast and would appreciate a nudge in the right direction.

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

Thanks.

Update: Following guidance from Thomas I came up with this function to extract Noteproperty members from a PSObject and return a Hashtable with the names of the fields and the values:

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
}

Thanks!

2
Can you show us the JSON you need to convert? - Theo

2 Answers

3
votes

You can access the members of a custom object like in any other object:

$myCustomObject.token

Reproduction:

$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

Output:

   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
1
votes

Since in your objects you store a string value, I see no other way to extract just the value silver then to use a string method to get only the part after the equals sign.

($obj.token -split '=', 2)[-1]  --> silver

Why not create the custom objects with an extra property called value and add the value you seek in there, taken from the Definition property? like

$obj = [PsCustomObject]@{'token' = 'string token=silver'; 'value' = 'silver'}