提供数组属性的数组的 Powershell 导出为 CSV

Powershell Export-to-CSV of array providing array properties

此代码:

$concerningMachines = @()
foreach($aMachine in $machineRecords.GetEnumerator())
{
    if($aMachine.Value.ReviewScore -gt $averageAboveAverage)
    {
        $machine = New-Object -TypeName PSObject
        $machine | Add-Member -MemberType NoteProperty -Name MachineName -Value $aMachine.Key
        $machine | Add-Member -MemberType NoteProperty -Name ManagedBy -Value $aMachine.Value.ManagedBy
        $machine | Add-Member -MemberType NoteProperty -Name LastLogin -Value $aMachine.Value.LastLogin
        $machine | Add-Member -MemberType NoteProperty -Name ReviewScore -Value ($aMachine.Value.ReviewScore / $averageAboveAverage * 100)
        $concerningMachines += $machine
    }
}

Export-Csv -InputObject $concerningMachines -Path C:\DG\ConcerningMachines.csv -NoTypeInformation

生成此 .csv 文件:

"Count","Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized" "43","43","43","1","System.Object[]","False","True","False"

...这是数组的属性,而不是数组的成员。谷歌搜索我发现的唯一建议似乎要么实施一个完全忽略 Export-Csv 的解决方案,要么处理字符串(虽然字符集合,但解决方案不适用)或者似乎正在做我已经在做的事情但是生成有效的 CSV 文件(如果需要,我可以找到一些链接,但它们是论坛对话,而不是明确的指南)。

如何正确地将一组 PSObject 导出到 CSV 文件中,并避免上述意外输出?

使用管道提供输入:

$concerningMachines| Export-Csv -Path C:\DG\ConcerningMachines.csv -NoTypeInformation

当您将相同的输入传递给 -InputObject 时,确实是 数组作为一个整体 被解释为 单个 要导出的对象。

此行为影响 所有 cmdlet,显然是 as designed:

InputObject is a single object to be processed. When used in a pipeline, InputObject is bound to each element in the pipeline and processed one at a time. If InputObject was processed as a collection, then each item from the pipeline would also be processed as a collection.

有些 cmdlet 对此行为很有用:例如,Get-Member,允许您使用 -InputObject 来检查集合的类型 作为一个整体,而管道输入检查 集合的每个元素

Export-CsvConvertTo-Csv 都不属于该类别,尽管 Get-Help ExportCsv 目前误导性地描述了 -InputObject 参数(强调) :

Specifies the objects to export as CSV strings. Enter a variable that contains the objects or type a command or expression that gets the objects. You can also pipe objects to Export-CSV.

务实的结论是总是使用管道(除非你真的想传递一个集合作为一个整体).

将数据放入 easy-to-read 格式的最好和最简单的方法之一是使用 CSV(comma-separated 值)文件。 CSV 文件将有一行 headers 来指示列名称和每列的后续值。 CSV文件中定位需要结构化数据

#looping the concerningMachines details to print in the excel cell
$concerningMachines | foreach { Add-Content -Path $FilePathLocation -Value $_ }