导出具有不同列数的数组

时间:2016-02-10 17:36:20

标签: powershell reporting powershell-v4.0

我正在尝试在Powershell中创建一个报告,但在尝试导出时遇到了问题。基本上我有一个循环,将数据添加到数组,但是当我去导出时,所有数据都不是导出。我把它打破了循环,所以我可以告诉你发生了什么。

我期待的是:

+----------+-----------+--------+
| HostName | Platform  | 3rdCol |
+----------+-----------+--------+
|  Test1   | Platform1 |        |
|  Test2   | Platform2 | 3rdCol |
+----------+-----------+--------+

我得到了什么:

+----------+-----------+
| HostName | Platform  |
+----------+-----------+
|  Test1   | Platform1 |
|  Test2   | Platform2 |
+----------+-----------+

Powershell的:

#Create report array
$report = @()

#New object for Test1
$stats = New-object PSCustomObject
#Hostname column for Test1
$stats | Add-Member -Name HostName -Value Test1 -Membertype NoteProperty
#Platform column for Test1
$stats | Add-Member -Name Platform -Value Platform1 -Membertype NoteProperty
#Add row to report
$report += $stats

#New object for Test2
$stats = New-object PSCustomObject
#Hostname column for Test2
$stats | Add-Member -Name HostName -Value Test2 -Membertype NoteProperty
#Platform column for Test2
$stats | Add-Member -Name Platform -Value Platform2 -Membertype NoteProperty
#3rd column for Test2
$stats | Add-Member -Name 3rdCol -Value 3rdCol -Membertype NoteProperty
#Add row to report
$report += $stats

#Export only has two columns instead of 3
$report | export-csv c:\temp\report.csv -notypeinformation

1 个答案:

答案 0 :(得分:2)

当PS输出数组时,它会查看第一条记录以确定需要哪些列,因此您需要确保您的第一条记录具有数组中任何成员的所有属性,即使该值是$null

如果您不知道这些属性是什么,那么您可以通过以下方式以编程方式获得该属性:

$Props=$report | ForEach{$_.PSObject.Properties} | Select -Expand Name -Unique
$Props|Where{$_ -notin $Report[0].psobject.properties.name}|ForEach{Add-Member -InputObject $Report[0] -NotePropertyName $_ -NotePropertyValue $null}