Parent Child Tree with powershell

This topic contains 3 replies, has 2 voices, and was last updated by  Jeremy Corbello 1 week, 4 days ago.

  • Author
    Posts
  • #86051

    Andreas
    Participant

    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

    Jeremy Corbello
    Participant

    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

    Andreas
    Participant

    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

      Jeremy Corbello
      Participant

      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 $($object.group)
      
          $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.
      https://www.powershellgallery.com/packages/Show-Tree/1.0.0/Content/Show-Tree.ps1

      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.

You must be logged in to reply to this topic.