Dyota's blog

PowerShell: get all descendants

Again?

It's kind of like this one, but this time in PowerShell.

I wrote this up because I was considering doing this outside of Power Query. Recursive functions can take up a lot of processing time, and if I can move this out of the PQ flow, I can speed up the overall refresh speed.

using namespace System.Collections.Generic; # for List

<#
This is the source data
"Name","Parent"
"Anakin Skywalker","Shmi Skywalker"
"Luke Skywalker","Anakin Skywalker"
"Leia Organa","Anakin Skywalker"
"Ben Skywalker","Luke Skywalker"
"Jaina Solo","Leia Organa"
"Jacen Solo","Leia Organa"
"Anakin Solo","Leia Organa"
"Allana Solo","Jacen Solo"
#>

$data = (Get-Content "./source.csv") | ConvertFrom-Csv -Delimiter ","

function getSubordinates ([string] $target) {
    return $data | Where-Object { $_.Parent -eq $target }
}

function getNextSubordinates ([List[string]] $targets) {
    return $targets | 
        ForEach-Object {
            getSubordinates $_
        }
}

function recurse ([List[string]] $targets) {
    
    if ($targets.Count -ne 0) {
        $subordinates = $targets | ForEach-Object {
            getNextSubordinates $_
        }
    
        $subordinates | ForEach-Object {
            [void] $out.Add($_.Name)
        }
        
        recurse $subordinates.Name
    }
    
}

[List[PSCustomObject]] $out = @()

[List[string]] $targets = @('Shmi Skywalker')

recurse $targets

$out

#powershell #recursive