Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing values of object properties in PowerShell

I'm going through an array of objects and I can display the objects fine.

$obj

displays each object in my foreach loop fine. I'm trying to access the object fields and their values. This code also works fine:

$obj.psobject.properties

To just see the names of each object's fields, I do this:

$obj.psobject.properties | % {$_.name}

which also works fine.

When I try to access the values of those field by doing this:

$obj.psobject.properties | % {$obj.$_.name}

nothing is returned or displayed.

This is done for diagnostic purposes to see whether I can access the values of the fields. The main dilemma is that I cannot access a specific field's value. I.e.

$obj."some field"

does not return a value even though I have confirmed that "some field" has a value.

This has baffled me. Does anyone know what I'm doing wrong?

like image 556
starcodex Avatar asked Jul 29 '13 15:07

starcodex


People also ask

How do you access the properties of an object in PowerShell?

To get the properties of an object, use the Get-Member cmdlet. For example, to get the properties of a FileInfo object, use the Get-ChildItem cmdlet to get the FileInfo object that represents a file. Then, use a pipeline operator ( | ) to send the FileInfo object to Get-Member .

How do you select a value from an object in PowerShell?

The Select-Object cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array. To select objects from a collection, use the First, Last, Unique, Skip, and Index parameters.

How do I get the value of a variable in PowerShell?

Description. The Get-Variable cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter, and you can filter the variables returned by name.

How do I print an object value in PowerShell?

The correct way to output information from a PowerShell cmdlet or function is to create an object that contains your data, and then to write that object to the pipeline by using Write-Output.


2 Answers

Once you iterate over the properties inside the foreach, they become available via $_ (current object symbol). Just like you printed the names of the properties with $_.Name, using $_.Value will print their values:

$obj.psobject.properties | % {$_.Value}
like image 193
Shay Levy Avatar answered Sep 20 '22 16:09

Shay Levy


Operator precedence interprets that in the following way:

($obj.$_).Name

which leads to nothing because you want

$obj.($_.Name)

which will first evaluate the name of a property and then access it on $obj.

like image 28
Joey Avatar answered Sep 18 '22 16:09

Joey