Powershell Export-CSV 忽略对象的非共享属性,我该如何解决这个问题?

Powershell Export-CSV ignores non-shared properties for objects, how can I get around this?

我在 powershell 2 中使用 Export-CSV 正确保存,但我希望它包含所有内容,如果它是空的,我想要空值。

$list | Export-Csv -Path (Get-SaveFile) -NoTypeInformation;

导出 CSV 的文档:

When you submit multiple objects to Export-CSV, Export-CSV organizes the file based on the properties of the first object that you submit. If the remaining objects do not have one of the specified properties, the property value of that object is null, as represented by two consecutive commas. If the remaining objects have additional properties, those property values are not included in the file.

我也不能简单地组织列表,因为有两个东西可能有 0 个或多个值。有些对象有注释,有些有 links,有些两者都有。但是我需要每个 link 1 列和每个评论 1 列,无论有多少,或 none。

是否有其他 cmdlet 可以实现这种不忽略任何字段的 export-csv 样式?

编辑答案: iRon 的这个 PowerShell 代码段正是我覆盖 Export-CSV 的 属性 截断所需要的。 https://powersnippets.com/union-object/ 感谢您的帮助!

如果您知道 CSV 文件中所需的特定属性,您可以将 Select-Object cmdlet 插入到管道中,如下所示:

$list | Select-Object prop1, prop2, prop3 | Export-Csv -Path (Get-SaveFile) -NoTypeInfo

如果您不知道具体属性,您可以扫描列表以生成一个属性列表。每个对象公开一个名为 PSObject 的 属性,其中包含另一个名为 Properties 的 属性。您可以扫描列表,获取列表中每个对象的属性名称,然后通过调用 Select-Object -Unique 来完成它,以获得一个没有重复的 属性 名称的漂亮列表。

$propList = $list | ForEach-Object {
        $_.PSObject.Properties | Select-Object -ExpandProperty Name
    } | Select-Object -Unique

$list | Select-Object $propList | Export-Csv -Path (Get-SaveFile) -NoTypeInformation