Lilly123
Lilly123

Reputation: 342

Storing output in CSV file

I have wriiten the following SQL script to execute using PowerShell.

cls
foreach ($svr in get-content "demo.txt")
{
  $con = "server=MC1-PQ10X.RF.LILLY.COM\SQL01;database=mylilly_WSS_Content_INCTSK0014840;Integrated Security=sspi" 

  $cmd = "SELECT
Docs.DirName + '/' + Docs.LeafName AS 'Item Name',
DocVersions.UIVersion, 
(DocVersions.UIVersion/512) as Version_Label, DocVersions.Level, DocVersions.TimeCreated
FROM DocVersions FULL OUTER JOIN Docs ON Docs.Id = DocVersions.Id
--   INNER JOIN Webs On Docs.WebId = Webs.Id
--INNER JOIN Sites ON Webs.SiteId = SItes.Id
WHERE (DirName LIKE '%globalcontentrepository%')
AND (IsCurrentVersion = '0')
AND (DocVersions.Id IN ('$svr'))"

  $da = new-object System.Data.SqlClient.SqlDataAdapter ($cmd, $con)

  $dt = new-object System.Data.DataTable

  $da.fill($dt) |out-null

  $dt | Export-Csv music.csv -Encoding ascii -NoTypeInformation
}

The problem I'm facing with the above code is regarding the output. For every $svr this code is creating a new CSV file. The input file is containing around 1000 inputs. My requirement is that all the output should get stored in the same file rather than creating new file.

Upvotes: 0

Views: 272

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

There are several ways to achieve your goal. One is to append to the output file as @PeterMmm suggested in the comments to your question:

foreach ($svr in Get-Content "demo.txt") {
  ...
  $dt | Export-Csv music.csv -Encoding ascii -NoTypeInformation -Append
}

Note, however, that Export-Csv doesn't support appending prior to PowerShell v3. Also, appending usually has a negative impact on performance, because you have to repeatedly open the output file. It's better to put the export cmdlet outside the loop and write the output file in one go. foreach loops don't play nicely with pipelines, though, so you'd have to assign the loop output to a variable first:

$music = foreach ($svr in Get-Content "demo.txt") {
  ...
  $dt
}
$music | Export-Csv music.csv -Encoding ascii -NoTypeInformation

or run it in a subexpression:

(foreach ($svr in Get-Content "demo.txt") {
  ...
  $dt
}) | Export-Csv music.csv -Encoding ascii -NoTypeInformation

Personally I'd prefer a ForEach-Object loop over a foreach loop, because the former does work well with pipelines:

Get-Content "demo.txt" | ForEach-Object {
  ...
  $dt
} | Export-Csv music.csv -Encoding ascii -NoTypeInformation

Note that you must replace every occurrence of your loop variable $svr with the "current object" variable $_ for this to work, though.

Upvotes: 4

Related Questions