Powershell Custom Sorting

64 Views Asked by At

I have below content in a txt file which will be read by powershell and should be rearranged based on a custom condition

File: abc.txt

General
User1/Alert
User1/LogicApp
General/Abc
User2/Alert
User2/LogicApp

Above should be sorted with custom condition where if "General" exists, it should be on top of the list and if string "LogicApp" exists, it should be next to General. Hence, output should be something like below

General
General/abc
User1/LogicApp
User2/LogicApp
User1/Alert
User2/Alert

If string "General" doesn't exist, then string "LogicApp" should be taking priority. Can we do this custom sorting in Powershell ?

2

There are 2 best solutions below

0
AdamL On

You can perform custom sorting using -Property parameter of Sort-Object, which accepts multiple expressions.

'General','User1/Alert','User1/LogicApp','General/Abc','User2/Alert','User2/LogicApp' | 
  Sort-Object -Property @{Expression={$_ -like '*General*'}; Descending=$true}, {if($_ -like '*LogicApp*') {0} else {1}}, {$_}

General and LogicApp are sorted using different methods just to illustrate. Last element {$_} assures alphabetical sort.

0
mklement0 On

To complement AdamL's helpful answer with a two-criterion solution using a switch statement to initially categorize the input strings, which is perhaps easier to conceptualize:

# Sample input lines.
$lines = @'
General
User1/Alert
User1/LogicApp
General/Abc
User2/Alert
User2/LogicApp
'@ -split '\r?\n'

$lines |
  Sort-Object -Property { 
      # 1st criterion: sort by presence of 'General', 'LogicApp', anything else, in order.
      switch -Regex ($_) { 'General' { 0 } 'LogicApp' { 1 } default { 2 } } 
    }, 
    { 
      # 2nd criterion: sort by the strings as a whole.
      $_ 
    }