Parent Child Tree with powershell

Welcome Forums General PowerShell Q&A Parent Child Tree with powershell

This topic contains 3 replies, has 2 voices, and was last updated by

1 year, 1 month ago.

  • Author
  • #86051

    Points: 1
    Rank: Member

    Hi all,

    i try to recursivly read groups from AD and want to display the output like a tree.
    therefore i created an object like this:

    ID : 15
    ParentID : 7
    AnzeigeName : DevAdmin
    SamAccountName : DevAdmin
    DistinguishedName : CN=DevAdmin,OU=Work,DC=forest1,DC=net
    FromGroup : CN=Domain Admins,CN=Users,DC=forest1,DC=net
    objectClass : user
    Level : 2

    ID : 7
    ParentID : 0
    AnzeigeName : Domain Admins
    SamAccountName : Domain Admins
    DistinguishedName : CN=Domain Admins,CN=Users,DC=forest1,DC=net
    FromGroup : CN=DLTest,CN=Users,DC=forest1,DC=net
    objectClass : group
    Level : 1

    How can i get all the objects sorted that all objects with ParrentID -eq X are displayed unter objects with ID -eq X??
    Any idea?

  • #86131

    Points: 22
    Rank: Member

    Just pipe the results to Group-Object

    $groupedData = $yourData | Group-Object ParentID

    Then, you will have all of your IDs in the "Name" column and the matches in the "Group" column. Manipulate that how you see fit.

  • #86183

    Points: 1
    Rank: Member

    Okay this worked so far i have a the parrentIDs and their childs.
    How can this help me to build a tree structure?
    So far I have one parent and one Child?

    • #86192

      Points: 22
      Rank: Member

      To start out, we want to group the parent and the child objects together:

      $tree = @()
      foreach ($object in $groupedData) {
          $data = New-Object psobject
          $data | Add-Member -Type NoteProperty -Name "Parent" -Value $(($yourData | where {$_.ID -eq $($object.Name)}))
          $data | Add-Member -Type NoteProperty -Name "Child" -Value $($
          $tree += $data

      At this point, $tree has the "Parent" value and each of the "Child" values. So it's purely cosmetic at this point.

      Look here for inspiration if you are wanting to create a tree-map.

      Otherwise, you can pipe $tree to something like ConvertTo-HTML, ConvertTo-JSON or ConvertTo-XML. XML or JSON would probably give you the closest to a tree without all of the additional coding.

The topic ‘Parent Child Tree with powershell’ is closed to new replies.