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

标签 sql powershell csv formatting

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

我正在尝试执行以下操作: 从几个内部连接的 SQL 表中读取 PowerShell 中的信息并将此信息保存在数据集中。这是我仍然能够做的:

$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

最佳答案

试试这个:

$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 '"'}

关于sql - PowerShell - 格式化 SQL 输出并将其写入 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11627396/

相关文章:

windows - 以编程方式启用 Powershell 是否可以接受?

bash - 如何在AWK中整理多个文件?

SQL优先级选择

mysql - Qt MySQL -------- 无法打开包含文件 : 'mysql.h' :

file - Powershell输出到文件和控制台

python - 用其他 .csv 中的列覆盖 .csv 中的列

amazon-web-services - Amazon Redshift - 从 CSV 复制 - 行中的单双引号 - CSV 错误的无效报价格式

mysql - sql 查找唯一值但只显示今天的日期

sql - 雅典娜 : Query exhausted resources at scale factor

powershell - 变量内每行的Powershell