2016-02-10 27 views
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 
+0

'出口-Csv'從推斷列標題*** ***先傳送給它的對象。代替僅將'3rdCol'屬性添加到* some *對象,將其添加到* all *對象(只需將它設置爲'$ null',以便不需要它的對象) –

+0

@ MathiasR.Jessen將在此工作例如,但是在循環中,我動態地創建了列,並且不知道將會有多少列。 – solar411

+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} 
+0

這將在這個例子中工作,但在一個循環中,我動態創建列,並不知道有多少列。 – solar411

+0

已更新,以照顧動態特性。 – TheMadTechnician

+0

謝謝!完美的作品。 – solar411