2

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 ?

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.
      $_ 
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.