views:

252

answers:

3

I'm doing a bit of Powershell scripting ( for the first time ) to look at some stuff in a Sharepoint site and what I would like to be able to do is to go through a list of properties of an object and just output their values in a "property-name = value" kind of format.

Now I can find the list of elements using this:

$myObject | get-member -membertype property

Which will return a list of all the properties in a very clear and readable fashion. But what I need is to find a value for those properties.

In some scripting languages I could have a kind of eval( "$myObject.$propertyName" ) call - where I have extracted $propertyName from the get-member output - and have it evaluate the string as code, which for the kind of quick-and-dirty solution I need would be fine.

Does this exist in Powershell or is there a more convenient way to do it? Should I be using reflection instead?

+2  A: 

To get the value of properties of an object, you can use several methods.

First off, you could use Select-Object and use the -Property parameter to specify which property values you would like returned. The how that is displayed will depend on the number of properties you specify and the type of object that it is. If you want all the properties, you can use the wildcard ( * ) to get them all.

Example -

$myobject | Select-Object -Property name, length
$myobject | Select-Object -Property *

You can also control the formatting of the outputs in a similar manner, using Format-List or Format-Table.

Example -

$myobject | Format-List -Property *
$myobject | Format-Table -Property name, length

Finally, to do an "eval" style output you could simply type

$myobject."$propertyname" 

and the value of the property will be returned.

Steven Murawski
I think you can even lose the quotes in that last code snippet:$myobject.$propertynameIt looks strange, but works.
Mike Shepard
This did the trick perfectly, thanks!
glenatron
A: 

For you purpose the best choice is Format-Custom.

get-date | Format-Custom -Depth 1 -Property * 
get-childitem . | select-object -first 1 | Format-Custom -Depth 1 -Property *

It's maybe too verbose, but useful ;)


Or you can really use Get-Member

$obj = get-date
$obj | 
   gm -MemberType *property | 
   % { write-host ('{0,-12} = {1}' -f $_.Name, $obj.($_.Name)) }
stej
A: 

For this I would recommend using Format-List -force e.g.:

Get-Process | Format-List * -Force

-Force is optional but sometimes PowerShell hides properties I really want to see.

Keith Hill