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

标签 powershell export-to-csv

这段代码:

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

务实的结论是始终使用管道(除非您真的想传递集合作为一个整体)。

关于提供数组属性的数组的 Powershell 导出为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44186288/

相关文章:

php - 创建合并 2 行的 CSV 并将值设置为 codeigniter 中的标题

javascript - 根据ui-grid的每行id将JSON数据导出到AngularJs中的CSV文件

python - 如何在python中比较两个列表列表,然后将数据写入excel

powershell - 无法写入 Google 表格((400)错误请求)

在服务下运行的 Powershell 卡在 *.zip CopyHere

windows - Powershell Open可执行文件,带有Program Files\WindowsApps内部的“开始”进程-拒绝访问

powershell - 如何在 PowerShell 中使用 Folder.CopyHere 覆盖现有项目?

python - 在 python 中已排序的 ("Error"字典的零索引位置插入列名称为 "Count", "error")

powershell - 从CSV/TXT创建文件夹并将匹配的列移到Powershell或Batch中的新目录中

powershell - 带有导出 CSV 的哈希表