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