Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Custom Sorting

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 ?

like image 669
psg20 Avatar asked Dec 31 '25 21:12

psg20


1 Answers

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.

like image 67
AdamL Avatar answered Jan 04 '26 03:01

AdamL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!