简体   繁体   English

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

[英]PowerShell - Formatting SQL output and writing it to CSV

I am kind of stuck with my problem and after searching the Web for a few hours I still didn't find a solution to it. 我有点困惑我的问题,在搜索网络几个小时后,我仍然没有找到解决方案。

I am trying to do the following: Reading Information in PowerShell from several inner joined SQL Tables and saving this information in a DataSet. 我正在尝试执行以下操作:从几个内部联接的SQL表中读取PowerShell中的信息,并将此信息保存在DataSet中。 This is what I am still able to do: 这是我仍然能够做到的:

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

Then export it to CSV like this: 然后将其导出为CSV,如下所示:

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

Now here comes the Problem. 现在问题来了。

My CSV looks something like this: 我的CSV看起来像这样:

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

My goal is to get a CSV that looks like this: 我的目标是获得一个如下所示的CSV:

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

How do I manage to get that? 我如何设法得到它?

EDIT: 编辑:

Ok got it to look like this: 好吧让它看起来像这样:

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

Has anyone got an idea how i can transform it into this syntax: 有没有人知道如何将其转换为这种语法:

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

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM