Powershell add header to blank csv

Mr Deans

I have a process that I am trying to fully automated and have hit upon a stumbling block.

The process runs through a number of SQL queries and then outputs these results to different named CSV files.

Where my issue lies is that where no results are returned in the query to the dataset when I export the data (which I must do to satisfy auditors) there is no header data written to the CSV file.

What I need to do therefore is IF the dataset contains 0 rows then to simply export a CSV file containing the headings "Client", "Balance", "Account".

Where as if there is data within the table then the process can continue as it currently does.

What I am is unsure how the hell this can be achieved...

I am currently muting whether or not I will have to export the data and then write a loop to delete any lines from the CSV containing for example "Client" then re-import the CSV's add the column heading that I want and export it again. As this is messy, ideally I would like to keep away from this..

Code is

$SqlCmd.CommandTimeout=$timeout;
$SqlCMD.CommandText = $034CASHQUERY;
$SqlCmd.Connection = $SqlConnection;

## - Extract Data and build sql data object

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];

IF($DataSet.Tables["Table"]){
$isnotnull
$DataSet.Tables["Table"] | Export-Csv $034CASHOUT -NoTypeInformation 
echo "CL2 Exported"


}
else {



}

Has anyone come across this before or aware of how to iterate through the issue?

ncooper09

You could create a .csv file and add the header text manually.

$headerText = ('"Client","Balance","Account"' + "`n")
New-Item $034CASHOUT | Add-Content -value $headerText 

Also, I think your IF condition may be a bit wonky. Are you looking for:

IF($DataSet.Tables["Table"] -isnot $null)

All together:

IF($DataSet.Tables["Table"] -isnot $null){

  $DataSet.Tables["Table"] | Export-Csv $034CASHOUT -NoTypeInformation 
  echo "CL2 Exported"

}
else {

  $headerText = ('"Client","Balance","Account"' + "`n")
  New-Item $034CASHOUT | Add-Content -value $headerText

}

This is probably not the best way to do it, but I think this is what you described.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related