PowerShell - 格式化SQL输出并将其写入CSV

时间:2012-07-24 08:54:56

标签: sql powershell csv formatting

我有点困惑于我的问题,在网上搜索了几个小时后,我仍然找不到解决方案。

我正在尝试执行以下操作: 从几个内部连接的SQL表中读取PowerShell中的信息,并将此信息保存在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 个答案:

答案 0 :(得分: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 '"'}