Public/Show-IAMCoreOrgUnitStructure.ps1

<#
.SYNOPSIS
    Displays the organizational unit structure in a tree format.

.DESCRIPTION
    This function takes a collection of organizational units (OrgUnits) and shows a tree format of the organizational structure.

.EXAMPLE
    Get-IAMCoreOrgUnit | Show-IAMCoreOrgUnitStructure

    This example retrieves all organizational units and displays their structure in a tree format.

.EXAMPLE
    Get-IAMCoreOrgUnit | Where-Object { $_.type.value -eq "company" } | Show-IAMCoreOrgUnitStructure

    This example retrieves organizational units with the type 'company' and displays their structure in a tree format.
#>

function Show-IAMCoreOrgUnitStructure {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        $InputObject
    )

    begin {
        $Script:OrgUnits = @{}
        $Script:Children = @{}
    }

    process {
        $Script:OrgUnits[$InputObject.Id] = $InputObject
        if ($InputObject.parent.value.objectId) {
            $Script:Children[$InputObject.parent.value.objectId] ??= @()
            $Script:Children[$InputObject.parent.value.objectId] += $InputObject.Id
        }
    }

    end {
        # Find top level nodes (those that either have parent as null or parent that is not in the list of org units)
        $Script:OrgUnits.Values | 
        Where-Object { -not $_.parent.value.objectId -or -not $Script:OrgUnits.ContainsKey($_.parent.value.objectId) } |
        Show-IAMCoreOrgUnitStructureHelper
    }
}