I need help with this script. Basically I am connecting to multiple databases to get a dataset I need. And after capturing the dataset from all different databases, I need to write output it to a CSV file. Below is the code I basically came up with. The script is creating an output CSV file but it doesn't append all the data I captured. It only writes the last dataset captured. How do I go around this?
Need help to fix it.
$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()
}