2012-07-24 96 views
3

我有點困擾我的問題,在搜索Web幾個小時後,我仍然沒有找到解決方案。PowerShell - 格式化SQL輸出並將其寫入CSV

我試圖執行以下操作: 在PowerShell中從幾個內部連接的SQL表中讀取信息並將此信息保存在DataSet中。這就是我依然能夠做到:

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
$SqlAdapter.SelectCommand = $command 
$DataSet = New-Object System.Data.DataSet 
$SqlAdapter.Fill($DataSet) 

然後將其導出爲CSV這樣的:

$DataSet.Tables[0] | Export-Csv -Delimiter "," C:\test.csv -Encoding "unicode" 

現在,這裏是問題。

我的CSV看起來是這樣的:

Servername,"Administrator","Description" 
SRV01,"Admin1","Description SRV01" 
SRV01,"Admin2","Description SRV01" 
SRV01,"Admin3","Description SRV01" 
SRV02,"Admin1","Description SRV02" 
SRV02,"Admin2","Description SRV02" 

我的目標是獲得一個CSV,看起來像這樣:

Servername,Administrator,Description 
SRV01,Admin1 Admin2 Admin3,Description SRV01 
SRV02,Admin1 Admin2,Description SRV02 

我怎麼弄到的?

編輯:

確定了它看起來像這樣:

Servername,Administrator,Description 
SRV01,Admin1,Description SRV01 
SRV01,Admin2,Description SRV01 
SRV01,Admin3,Description SRV01 
SRV02,Admin1,Description SRV02 
SRV02,Admin2,Description SRV02 

有沒有人有一個想法如何,我可以將它轉換成語法:

Servername,Administrator,Description 
SRV01,Admin1 Admin2 Admin3,Description SRV01 
SRV02,Admin1 Admin2,Description SRV02 
+1

只要CSV是關注。你會如何對待嵌入的引號或逗號? – Joey 2012-07-24 09:20:28

回答

2

試試這個:

$csv = @" 
Servername,Administrator,Description 
SRV01,Admin1,Description SRV01 
SRV01,Admin2,Description SRV01 
SRV01,Admin3,Description SRV01 
SRV02,Admin1,Description SRV02 
SRV02,Admin2,Description SRV02 
"@ 

$group = ConvertFrom-Csv $csv | Group-Object -Property Servername,Description 

$group | select @{n='Name';e={ ($_.Name -split ",")[0] }}, @{n='Administrators';e={ ($_.Group | select -expandproperty Administrator) -join ","}}, @{n='Description';e={ ($_.Name -split ",")[1] }} | 
convertto-csv -NoTypeInformation | Foreach-Object -begin { $start=$true } -process { if ($start) { $start=$false } else { $_ } } | foreach {$_ -replace '"'} 
+0

完全做了這個把戲,非常感謝你! – t1red 2012-07-24 15:20:05