Small report for Sql is displaying the columns in an incorrect order when exporting to csv file

StackOverflow https://stackoverflow.com/questions/22537574

  •  18-06-2023
  •  | 
  •  

Question

I am writing a basic script in Power shell to learn it for part of my employment project I am on. I am currently a .NET developer, but spanking new to power shell. Just started yesterday actually. Anyways, can anyone take a look at this script, and let me know why the order of the columns in the output file does not match the correct order of our sql query?

The concept is to read it into array, using objects for each row. Any help would be greatly appreciated. Thanks!

Here is the script below, minus connection stuff.

########################################
#
#  USED TO GET RESULTS AND EXPORT TO SQL 
#
#
########################################



################################################
#   Lets first make sure we have the dates before we do anything else
################################################

$argsLength = $args.Length;

if($argsLength -lt 2)
{

  Write-Host "You must suply a date range in the format (from, to)."
  Write-Host "Example: PS> [command] from to : format [yyyy-mm-dd]";

}
else
{

   ###########################
   # Get the dates supplied by as params ###
   ###########################
   $from = $args[0];
   $to = $args[1];


   ###########################
   # Notify user job is now running
   ###########################
   Write-Host "Building report for dates " $from " to " $to "..."

   ###########################
   #Write-Host 'Get connection to SQL database'
   ###########################
   Try 
   {
     $Connection = New-Object System.Data.SQLClient.SQLConnection
     $Connection.ConnectionString = 
     $Connection.Open()
     $Command = New-Object System.Data.SQLClient.SQLCommand
     $Command.Connection = $Connection          

     $Connection2 = New-Object System.Data.SQLClient.SQLConnection
     $Connection2.ConnectionString = 
     $Connection2.Open()
     $Command2 = New-Object System.Data.SQLClient.SQLCommand
     $Command2.Connection = $Connection2 

   }
   Catch 
   {
     Throw "Can't connect to database..."
   }    

   ###########################
   #Write-Host 'Execute query'      
   ###########################
   $Command.CommandText = "SELECT job_number, job_desc, permit_number, pieces, rate, postage_total FROM monticello_charges WHERE (insert_date >= '$from') AND (insert_date < '$to') ORDER BY job_number"
   $Command2.CommandText = "SELECT job_number, description, permit_number, pieces, rate, total FROM mailshop_charges WHERE (mailing_date >= '$from') AND (mailing_date < '$to')ORDER BY permit_number, job_number"

   $Reader = $Command.ExecuteReader() 
   $Reader2 = $Command2.ExecuteReader()  

   ##### Do not add entries that have a [permit_number] of (360) and [rate] less than (0) ### #
   $results = @()
   while ($Reader.Read())
   {
        $row = @{}        
        for ($i = 0; $i -lt $Reader.FieldCount; $i++)
        {
            if($reader.GetValue(2) -eq 360 -and $reader.GetValue(4) -lt 0)
        {
              #pass over it
            }
            else
            {
               $row[$reader.GetName($i)] = $reader.GetValue($i)
            }             
        }
        $results += new-object psobject -property $row 
   }


   ##### Build the second table and replace 280 permits to (M) ###
   $results2 = @()
   while ($Reader2.Read())
   {       
        $row = @{}
        for ($i = 0; $i -lt $Reader2.FieldCount; $i++)
        {
            if($i -eq 2 -and $reader2.GetValue($i) -eq 280)
        {
              $row[$reader2.GetName($i)] = "M"
              $counter++
            }
            else
            {
               $row[$reader2.GetName($i)] = $reader2.GetValue($i)
            }             
        }
        $results2 += new-object psobject -property $row            
   }


   $finalResult = $results + $results2;

   $finalResult = $finalResult | sort-object @{Expression={$_.job_number}; Ascending=$true}

   $finalResult = $finalResult | sort-object @{Expression={$_.permit_number}; Ascending=$true}



    $finalResult | export-csv .\out.csv

    Write-Host "Report has been exported to current directoy. Filename:[out.csv]"
}
Was it helpful?

Solution

That's because you're using a hash table, and hash tables may not enumerate in the same order they were declared. If you have Powershell V3, you can use the [ordered] type accelerator to create an ordered hash table, and it will maintain the same order that the keys were created in:

$row = [ordered]@{} 

Or you can use Select-Object on your object collection ($finalresult) to set the order that you want before you do the export.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top