Search code examples
powershell-3.0

Dynamically get PSCustomObject property and values


I have the following:

$test = [pscustomobject]@{
    First = "Donald";
    Middle = "Fauntleroy";
    Last = "Duck";
    Age = 80
}
$test | Get-Member -MemberType NoteProperty | % {"$($_.Name)="}

which prints:

Age=
First=
Last=
Middle=

I would like to extract the value from each property and have it included as the value for my name value pairs so it would look like:

Age=80
First=Donald
Last=Duck
Middle=Fauntleroy

I am trying to build a string and do not know the property names ahead of time. How do I pull the values to complete my name value pairs?


Solution

  • The only way I could find (so far) is to do something like:

    $test = [pscustomobject]@{
        First = "Donald";
        Middle = "Fauntleroy";
        Last = "Duck";
        Age = 80
    }
    
    $props = Get-Member -InputObject $test -MemberType NoteProperty
    
    foreach($prop in $props) {
        $propValue = $test | Select-Object -ExpandProperty $prop.Name
        $prop.Name + "=" + $propValue
    }
    

    The key is using -ExpandProperty.