I am new to powershell scripting. Apologies if I am missing something simple.
Let's say I have an object called object
that has a field called field
. Now let there be a list of these objects.
How would I get the list of fields in the same order?
In python it would be:
list_of_objects = [o1, o2, o3]
list_of_fields = [i.field for i in list_of_object]
powershell is nice, and not so nice, because it unwraps collections for you, and sometimes this can hide that it is masking the elements' members. When you're using $parents.item
, you're accessing the array's method, and trying to access its members (which there aren't any, so powershell is giving you $null
):
Item ParameterizedProperty System.Object IList.Item(int index) {get;set;}
You can overcome this by using the method I shared in the comments to iterate over each member and avoid this masking:
$list = $parents | ForEach-Object -MemberName item
$list.registration.parentCompoundNumber
Alternatively, a syntax more people are familiar with:
$list = $parents | Select-Object -ExpandProperty item
or unrolling it yourself:
# you could directly assign the outputs of a `foreach` loop to a variable by
# removing these comments (<##>)
<# $items = #>
foreach ($parent in $parents) {
$parent.item.registration.parentCompoundNumber
}
To see when this masking is happening, consider this example which uses the unary array operator:
, @('a', 'b', 'c') | Get-Member
This will let you observe the wrapping array or collection's members.