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?
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 .
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.
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.
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.
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}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With