【问题标题】:How to expand (flatten) row in datatable which in one of columns contains array?如何扩展(展平)数据表中其中一列包含数组的行?
【发布时间】:2012-05-12 03:48:30
【问题描述】:

有没有办法扩展/展平数据表中的行?我在有 2 列的变量 $table 中有数据。在第一列中存储了 [string] 值,而在第二列中存储了 [string[]] 数组值,其中至少包含 2 个值。下面是这样一行的示例:

DistinguishedName                       GroupNames
-----------------                       ----------
Applications/FarmName/Notepad           {Domain\Group1, Domain\Group2}

我希望将其展平并导出到例如CSV 格式,而第一列保留“键值” DistinguishedName,所有其他列都填充有从 GroupNames 列扩展的特定值。所需输出示例如下:

Applications/FarmName/Notepad; Domain\Group1; Domain\Group2

【问题讨论】:

标签: .net powershell datatable system.array


【解决方案1】:

如果您打算导出到 csv,可能的解决方案可能是创建自己的 PSObject 并动态填充它的属性。

类似这样的:

$expandedObjects = @()
$table | % {
    #assuming $_ reffers to actual row

    $obj = new-object PSObject
    $obj | Add-Member -MemberType NoteProperty -Name "DistinguishedName" -Value $_.DistinguishedName

    $i = 0 # for dynamic property naming
    $_.GroupNames | % {
        # assuming $_ reffers to actual GroupName value
        $obj | Add-Member -MemberType NoteProperty -Name $("GroupName{0}" -f $i++) -Value $_
    }
    $expandedObjects += $obj
}
$expandedObjects | export-csv ..

我没有测试代码,所以可能会有一些错误。另外我不知道您的 $table veriable 到底是什么类型。但是思路应该很清楚。

【讨论】:

  • 脚本需要稍微修正,而 scriptblock 不会被评估。 {"GroupName{0}" -f $i++} 应替换为 $("GroupName{0}" -f $i++)。
猜你喜欢
  • 2016-03-16
  • 2019-10-24
  • 2023-01-19
  • 2016-11-29
  • 1970-01-01
  • 2020-09-21
  • 2018-12-27
  • 2015-03-19
  • 2016-05-10
相关资源
最近更新 更多