20

我正在编写一个 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

4 回答 4

29

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

$changesets | Select-Object ChangeSetId, Owner, Comment,
    @{Name="Changes"; Expression={ $_.Changes | Select-Object ChangeType, ServerItem }} |
Select-Object -Property * -ExcludeProperty Changes -ExpandProperty Changes
于 2016-03-02T12:37:58.207 回答
9

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

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

如果您希望嵌套对象成为顶级元素,您也可以这样做......

$changesets | Select-Object `
ChangeSetId,
Owner,
Comment,
@{Name="ChangeType"; Expression={ $_.Changes.ChangeType}},
@{Name="ServerItem"; Expression={ $_.Changes.ServerItem }}
于 2016-03-02T10:36:24.107 回答
5

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

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

账单

于 2013-04-04T17:39:11.377 回答
2

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

$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
于 2021-01-11T09:01:55.663 回答