0

At the end you can find my code snippet. In code that is not in the snippet $tree = OrgTree-Create($inputfile) I create a tree of nodes. The nodes are represented by the class OrgUnit.

As you can see this class has a parents attr that is a HashSet of strings. The tree is correctly created, I've done some testing and all looks well.

So I created a simple node --> root representation function called PrintBranchUp. Here is where I quickly ran into trouble.

The behaviour that I saw as that the first node was correctly added, makes sense.

$branch.Add($node)

The second node is also correctly added but then the THIRD one just returned on letter.. So somehow the second iteration of the loop made $parents = $tmp.parents behave as a string instead of a hashset? It took me a very longtime to fix it (which I did) but I don't understand why.

So the issue was that apparently $node = $parents[0] in iteration 1 does not return a string from the hashset, but a hashset.. However when I printed it during debug it looks just like a string. And the next call of $tmp = $tree[$node] will actually return the next node correctly. It's only when the parents of it is called that parents becomes a string instead of a hashset.

Can someone explain this behaviour? I really can NOT wrap my head around it. What fixed it in the end was casting $node to string. $tmp = $tree[[String]$node] which is just silly.

Class OrgUnit
{
    [String]$name
    $parents
    $children
    $members


    OrgUnit($name){
        $this.name = $name
        $this.parents = New-Object System.Collections.Generic.HashSet[string]
        $this.children = New-Object System.Collections.Generic.HashSet[string]
        $this.members = New-Object System.Collections.Generic.HashSet[string]
    }
}



Function PrintBranchUp($tree, $node){

    $branch = New-Object System.Collections.Generic.List[string]
    $branch.Add($node)

    while($true){
        $tmp = $tree[$node]
        $parents = $tmp.parents
        if($parents.Count -gt 0){
            $node = $parents[0]
            $branch.Add($node)
        }
        else{
            break
        }
    }

    return $branch
}



# $tree = OrgTree-Create($inputfile)

$tmp = "Business Unit"
$branch = PrintBranchUp $tree $tmp
Spyral
  • 760
  • 1
  • 12
  • 33
  • 1
    Does this answer your question? [ArrayList Unrolling](https://stackoverflow.com/questions/12916840/arraylist-unrolling) (generally, search for the words `PowerShell unroll`, you will find a lot of similar issues and explanations to those.) – iRon Nov 16 '19 at 08:08
  • If you want help with existing code, please post the full code to reproduce the issue (Where is `OrgTree-Create` defined?) – Mathias R. Jessen Nov 17 '19 at 11:41

0 Answers0