Mike Cheel
Mike Cheel

Reputation: 13116

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?

Upvotes: 15

Views: 31530

Answers (7)

0x4161726f6e
0x4161726f6e

Reputation: 1

While this doesn't format as requested it does allow for additional processing and doesn't require additional variables.

$Test.psobject.members `
| Where-Object MemberType -EQ 'NoteProperty' `
| Select-Object name,value

Output:

Name    Value
----    -----
Age     80
First   Donald
Last    Duck
Middle  Fauntleroy

To achieve requested formatting

$Test.psobject.members `
| Where-Object MemberType -EQ 'NoteProperty' `
| Foreach-Object {
    "$($_.name) = $($_.value)"
}

Output:

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

Upvotes: 0

Dmitry Trukhanov
Dmitry Trukhanov

Reputation: 202

A shorter way for this old problem. You can use:

$test.PSObject.Properties | %{Write-Output "$($_.Name)=$($_.Value)"}

If you want to access some field programmatically in runtime, by using variable as a field selector, then you can use:

$myProperty = "Age"
$test.PSObject.Properties[$myProperty].Value

Upvotes: 3

Emiliano Poggi
Emiliano Poggi

Reputation: 24846

I use:

$MyObjectProperties = Get-Member -InputObject $MyObject -MemberType NoteProperty

$MyObjectProperties | % {
    $PropertyName = $_.Name
    $PropertyValue = $MyObject."$PropertyName"
    # ...
}

Upvotes: 0

KhaAlex
KhaAlex

Reputation: 41

My variant:

$memberNames = ($test | Get-Member -Type NoteProperty).Name
foreach ($mname in $memberNames) {
    "{0}={1}" -f $mname,$Test."$mname"
}

Upvotes: 2

Boklucius
Boklucius

Reputation: 1926

Not sure if it is really better, but here's one more variant:

$test.psobject.Members | ? {$_.Membertype -eq "noteproperty"} | 
    %{ $_.Name + '='+  $_.Value }

Upvotes: 5

scobi
scobi

Reputation: 14558

Shorter, more PowerShell'ish option:

$test | Get-Member -MemberType NoteProperty | % Name | %{
    $_ + '=' + $test.$_
}

Upvotes: 11

Mike Cheel
Mike Cheel

Reputation: 13116

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.

Upvotes: 22

Related Questions