嵌套集合上的Select-Object

时间:2013-04-04 16:19:40

标签: powershell tfs

我正在编写一个Powershell cmdlet来列出来自TFS的更改集。我成功查询TFS并获取变更集的集合,但希望返回仅包含少量属性的简化对象。我可以使用Select-Object这样做......

$changesets | Select-Object ChangeSetId, Owner, Comment

我想要添加的最后一个属性是Changes属性,它是一组更改。我也希望简化这些对象。我正在尝试这个,但它没有返回我想要的东西......

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

有没有办法用Select-Object处理嵌套集合?

4 个答案:

答案 0 :(得分:16)

您可以使用-ExpandProperty cmdlet的Select-Object参数。它将扩展集合并将父对象中的选定属性添加到子对象:

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

答案 1 :(得分:4)

我可能会为内部集合中的每个项目展开内部集合和输出一次。这样的事情(未经测试):

$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
    }
  }
}

比尔

答案 2 :(得分:3)

你的表达式语法不是很正确,你需要在表达式和代码块之间使用等号(" =")。

controls.customRotate(Math.PI/2)

如果您希望嵌套对象成为未来的顶级元素,您也可以...

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

答案 3 :(得分:1)

或者,将更改的数组压缩为字符串:

$changesets = ConvertFrom-Json '[{"ChangeSetId":1,"Owner":"foo","Comment":"bar","Changes":[{"ChangeType":"la", "ServerItem":"some"}, {"ChangeType":"so", "ServerItem":"stuff"}]}, {"ChangeSetId":2, "Owner":"bar", "Comment":"baz", "Changes":[{"ChangeType":"ti", "ServerItem":"other"}, {"ChangeType":"doh", "ServerItem":"stuff"}]}]'
$changesets | % {`
    [pscustomobject]@{
    ChangeSetId = $_.ChangeSetId
    Owner       = $_.Owner
    Comment     = $_.Comment
    Changes     = ($_.Changes | Select @{Name = "foo"; Expression = {$_.ChangeType + ' ' + $_.ServerItem}} | Select -ExpandProperty foo) -join "; "
  }
}
ChangeSetId Owner Comment Changes
----------- ----- ------- -------
          1 foo   bar     la some; so stuff
          2 bar   baz     ti other; doh stuff