Powershell脚本,用于将结果集从多个源追加到csv

时间:2014-07-28 21:09:03

标签: powershell

我需要这个脚本的帮助。基本上我连接到多个数据库以获取我需要的数据集。在从所有不同数据库捕获数据集之后,我需要将输出写入CSV文件。以下是我基本提出的代码。该脚本正在创建输出CSV文件,但它不会附加我捕获的所有数据。它只写入捕获的最后一个数据集。我该如何解决这个问题?

需要帮助才能解决问题。

$DB = Get-Content c:\ps\DBLIST.txt
foreach($Data in $DB)

{

Write-Host $Data
$strDB = $Data+".local"

$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = "Server=$strDB;Database=db;User ID=user;Password=password"
$con.open()

$qry = "select a, b, c, d from table1"

$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.CommandText = $qry
$cmd.Connection = $con

$da = New-Object System.Data.SqlClient.SqlDataAdapter
$da.SelectCommand = $cmd
$ds = New-Object System.Data.Dataset
$da.Fill($ds)
$dr = $cmd.ExecuteReader()

Write-Host

$outFile = "C:\ps\OUTPUT.csv" 


    If ($dr.HasRows)
        {


          write-Host a     b     c     d

          While ($dr.Read())
            {

            Write-Host $dr["a"]         $dr["b"]        $dr["c"]        $dr["d"]

            }

        }
    Else
        {
          Write-Host There are no records found.  Try again.
        } 

$ds.Tables[0] | export-csv $outFile -NoTypeInfo -Force -Append
#$ds.Tables[0] | Export-Csv -Delimiter ','$outFile -Encoding "unicode"

Write-Host

$dr.Close()
$con.Close()

}

2 个答案:

答案 0 :(得分:1)

这应该有效

$SomeObject | export-csv $outFile -NoTypeInfo -Append

编辑PowerShell v2,其中-Append不存在: 收集一个对象中的所有信息。完成后将此对象写入文件。

# before you start the loop:
$a = @()

# in your loop:
$a += $ds.Tables[0]

# after the loop:
$a | Export-Csv $outFile -NoTypeInformation

答案 1 :(得分:1)

您可以通过Foreach-Object使用Powershell管道,而不是ForEach循环。如果您将数据库服务器列表发送到管道中,然后只是在循环内输出结果,Powershell会将所有结果发送到管道中,从而有效地组合它们。然后,您可以获取最终结果并将其写入CSV文件。

请注意,我必须将$ outfile变量移动到循环之上(无论如何它都属于它)。当我在Powershell v2.0中测试它时,我还必须明确标记-Path参数:

$outFile = "C:\TEMP\OUTPUT.csv" 

$DB = Get-Content c:\ps\DBLIST.txt
$DB | Foreach-Object {
    $Data = $_
    $strDB = $Data+".local"

    $con = New-Object System.Data.SqlClient.SqlConnection
    $con.ConnectionString = "Server=$strDB;Database=db;User ID=user;Password=password"
    $con.open()

    $qry = "select a, b, c, d from table1"

    $cmd = New-Object System.Data.SqlClient.SqlCommand
    $cmd.CommandText = $qry
    $cmd.Connection = $con

    $da = New-Object System.Data.SqlClient.SqlDataAdapter
    $da.SelectCommand = $cmd
    $ds = New-Object System.Data.Dataset
    $da.Fill($ds) | Out-Null   # prevent the number of records from going down the pipeline
    $dr = $cmd.ExecuteReader()

    # This is the magic right here -- it simply outputs the
    # contents of $ds.Tables[0] to the pipeline
    $ds.Tables[0] 

    $dr.Close()
    $con.Close()

} | Select-Object a,b,c,d  | Export-Csv -Path $outFile -Delimiter ',' -Encoding "unicode"
相关问题