Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 993
Mike Cheel Avatar asked Nov 28 '14 20:11

Mike Cheel


1 Answers

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.

like image 100
Mike Cheel Avatar answered Dec 03 '22 19:12

Mike Cheel