Select-Object for nested collections

I am writing a Powershell cmdlet to list changesets from TFS. I successfully request TFS and get a collection of change sets, but I want to return simplified objects that contain only a few properties. I can do it with Select-Object like this ...

 $changesets | Select-Object ChangeSetId, Owner, Comment 

The last property I would like to add is the Changes property, which is an array of changes. I would also like to simplify these objects. I am trying to do this, but it does not return what I want ...

 $changesets | Select-Object ` ChangeSetId, Owner, Comment, @{Name="Changes"; Expression={ $_.Changes | Select-Object ChangeType, ServerItem }} 

Is there a way to handle nested collections using Select-Object ?

+4
source share
3 answers

Perhaps you are using the -ExpandProperty parameter of the Select-Object . It will expand the collection and add selected properties from the parent to the children:

 $changesets | Select-Object ChangeSetId, Owner, Comment, @{Name="Changes"; Expression={ $_.Changes | Select-Object ChangeType, ServerItem }} | Select-Object -Property * -ExcludeProperty Changes -ExpandProperty Changes 
+7
source

I would probably expand the inner collection and output once for each element in the inner collection. Something like this (not verified):

 $changesets | foreach-object { $changeSetItem = $_ $changeSetItem.Changes | foreach-object { $changeItem = $_ new-object PSObject -property @{ "ChangeSetId" = $changeSetItem.ChangeSetId "Owner" = $changeSetItem.Owner "Comment" = $changeSetItem.Comment "ChangeType" = $changeItem.ChangeType "ServerItem" = $changeItem.ServerItem } } } 

Bill

+4
source

The syntax of the expression is not quite right, you need an equal expression ("=") between the expression and the code block.

 $changesets | Select-Object ` ChangeSetId, Owner, Comment, @{Name="Changes"; Expression={ $_.Changes | Select-Object ChangeType, ServerItem }} 

If you want the nested object to be a top level element going forward, you could also do ...

 $changesets | Select-Object ` ChangeSetId, Owner, Comment, @{Name="ChangeType"; Expression={ $_.Changes.ChangeType}}, @{Name="ServerItem"; Expression={ $_.Changes.ServerItem }} 
+3
source

All Articles