Problem : Sorting an Excel worksheet with header row in powershell

Problem : Sorting an Excel worksheet with header row in powershell

I’m trying to learn powershell from a vbscript background and for the life of me I can’t figure out how to properly sort a worksheet in powershell.

I want to sort descending on column H, but I have a header row, so I’d like to start on cell H2.

How would I do something like this? And how would I sort on 2 separate columns? I can’t seem to find any references specifically for powershell on the web.

1:
2:
3:
4:
5:
6:
$excel = New-Object -ComObject excel.application
$excel.visible=$true
$wb = $excel.Workbooks.Open("C:\scripts\worksheet.xls")
$ws = $wb.Worksheets.item(1)
$range=$ws.usedrange
$range.Sort($ws.range("h2"),2)

Solution : Sorting an Excel worksheet with header row in powershell

Though the official VBA syntax is

Sort(Key1, Order1, Key2, Type, Order2, Key3, Order3, Header, OrderCustom, MatchCase, Orientation, SortMethod, DataOption1, DataOption2, DataOption3)

> $range.Sort
outputs the following syntax:

MemberType          : Method
OverloadDefinitions : {Variant Sort (Variant, XlSortOrder, Variant, Variant, XlSor
tOrder, Variant, XlSortOrder, XlYesNoGuess, Variant, Variant
, XlSortOrientation, XlSortMethod, XlSortDataOption, XlSortD
ataOption, XlSortDataOption)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : Variant Sort (Variant, XlSortOrder, Variant, Variant, XlSort
Order, Variant, XlSortOrder, XlYesNoGuess, Variant, Variant,
XlSortOrientation, XlSortMethod, XlSortDataOption, XlSortDa
taOption, XlSortDataOption)
Name                : Sort
IsInstance          : True

The two variants after the first XlSortOrder are puzzling. I tried and had success by ignoring the first variant of those:

> $range.Sort($ws.Range(“J:J“), 2, $null, $ws.Range(“H:H”), 2)

But don’t ask me more – has been my first time I tried to access Excel thru PS. It is not the way PS is supposed to be used – Chris-Dent’s approach is in fact PS-stylish.