Search code examples
powershell-3.0

How to Sort a specific column A-Z in Powershell?


I have a PowerShell script that is converting a .csv file into .xlsx but now I have an additional requirement is to sort (Lowest to Highest) a specific column in file.Column "G".Any suggestion ?

My existing code is below.

Function conversion($inputCSV,$outputXLSX)
{


    ### Create a new Excel Workbook with one empty sheet
    $excel = New-Object -ComObject excel.application 
    $workbook = $excel.Workbooks.Add(1)
    $worksheet = $workbook.worksheets.Item(1)


    ### Build the QueryTables.Add command
    ### QueryTables does the same as when clicking "Data » From Text" in Excel
    $TxtConnector = ("TEXT;" + $inputCSV)
    $Connector =$worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))

    $query = $worksheet.QueryTables.item($Connector.name)

    ### Set the delimiter (, or ;) according to your regional settings
    $query.TextFileOtherDelimiter = $Excel.Application.International(5)

    ### Set the format to delimited and text for every column
    ### A trick to create an array of 2s is used with the preceding comma
    $query.TextFileParseType  = 1
    $query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
    $query.AdjustColumnWidth = 1

    ### Execute & delete the import query
    $query.Refresh()
    $query.Delete()



    ### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
    $Workbook.SaveAs($outputXLSX,51)
    $excel.Quit()
}

$inputCSV= "C:\Users\Desktop\Book2.csv"
$outputXLSX = "C:\Users\Desktop\Book2_sorted.xlsx"

conversion $inputCSV,$outputXLSX

Solution

  • I commend to your attention the information obtainable by entering Get-Help -Name Sort-Object -Full. Assuming, for the purposes of discussion, that your Column G has a header of "G" in the CSV file, you would want some code along the lines of

    Import-CSV -Path $inputcsv | Sort-Object -Property G | Export-CSV -Append -Path $sortedcsv -NoTypeInformation
    

    and then pass $sortedcsv to your workbook-building routine.