powershellsortingdependenciescomparetopological-sort

How to do a topological sort in PowerShell


For my own implementation of a Build-Module, I am in need to sort an array of functions and classes based on its dependencies. A similar question How to sort array of dependencies? has a helpful hint but it doesn't include any code. The question Topological Sorting using LINQ does include code but only C# based.

Therefore I decided to create simple data set of PSCustomObjects to be able to test my idea with a Minimal, Reproducible Example (in my own answer) before putting it in my full blown project:

$Array = ConvertFrom-Json @'
[
  { "Name": "Function1", "Dependency": ["Function3"] },
  { "Name": "Function2", "Dependency": ["Function3", "Function4", "Function5"] },
  { "Name": "Function3", "Dependency": [] },
  { "Name": "Function4", "Dependency": ["Function1", "Function5"] },
  { "Name": "Function5", "Dependency": ["Function1"] }
]
'@

The task is to sort the objects so that any object that is required by an other object is loaded first, meaning the expected result order should look like:

Name      Dependency
----      ----------
Function3 {}
Function1 {Function3}
Function5 {Function1}
Function4 {Function1, Function5}
Function2 {Function3, Function4, Function5}

I have put my own answer below as possible approach and reuse but welcome any other comment or answer to tackle a topological sort in PowerShell differently.


Solution

  • Despite the attention on the meta issues in my question, apparently nobody got the design bug in my original (deleted) self-answer.

    In the end, I think that I can conclude that using a comparer for this isn't the correct way to go therefore I have created a Sort-Topological to do the job.