这段代码:
$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-Csv
和 ConvertTo-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/