Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Powershell have an "eval" equivalent? Is there a better way to see a list of properties and values?

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?

like image 849
glenatron Avatar asked Mar 17 '10 17:03

glenatron


3 Answers

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.

like image 57
Steven Murawski Avatar answered Oct 19 '22 12:10

Steven Murawski


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)) }
like image 45
stej Avatar answered Oct 19 '22 10:10

stej


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.

like image 40
Keith Hill Avatar answered Oct 19 '22 12:10

Keith Hill