Dynamically retrieve PSCustomObject properties 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 a value from each property and include it as a value for the value pairs of the name, so that it looks like this:

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

I am trying to create a string and do not know the property names ahead of time. How can I pull values ​​to populate name pairs?

+6
source share
4 answers

The only way I could find (for now) 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 uses -ExpandProperty

If someone has a more concise way to do this, write!

+7
source

Shorter, more convenient option:

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

Not sure if this is really better, but here is another option:

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

My version:

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

Source: https://habr.com/ru/post/978849/


All Articles