I have been trying to create a script to map out an Active Directory's OU structures. (The end goal would be to have the equivalent of the windows tree.com command.)
For the following folder structure:
- Domain.local
- Domain Controllers
- Users
- Internal
- External
Would have the following Output:
[Domain.local]
Domain Controllers
Users
Internal
External
The code used to do it would be the following:
function Display-OU{
param(
[String]$ParentOU,
[System.Collections.ArrayList]$ChildOUs
)
# $ChildOUs
$ChildOUs | ForEach-Object{$_.DN.Remove($_.Name)}
if($ParentOU){
$Spacing = " "
}else{
$Spacing = ""
}
$Return = foreach($cOU in $ChildOUs){
if($cOU.DN){
Continue
}
$Parent = $cOU.Name
"$Spacing$($cOU.Name)"
$Children = $ChildOUs | Where-Object{$_.DN -contains $Parent}
if($Children){
"$Spacing$(Display-OU -ParentOU $ParentOU -ChildOUs $Children)"
}
}
return $Return
}
# Recover the OU data
$Raw = Get-ADOrganizationalUnit -Filter * | Select Name,DistinguishedName
# Clean up the data
$OUs = foreach($Entry in $Raw){
[PsCustomObject]@{
Name = $Entry.Name
Domain = ($Entry.DistinguishedName.Split(",") | Where-Object{$_ -match "DC="}) -join "." -replace "DC="
DN = [System.Collections.ArrayList](($Entry.DistinguishedName -replace '\,DC=.+').Split(",") -replace "OU=")
}
}
# Run the command depending on the number of domains
$Domains = $OUs.Domain | Select -Unique
foreach($D in $Domains){
$dOUs = $OUs | Where-Object{$_.Domain -eq $D}
Write-Host "[$D]"
Display-OU -ChildOUs $dOUs
}
I am guessing I am doing something wrong when defining the variables, because I keep getting the following Output:
[testdomain.local]
Domain Controllers
Test_Domain_Users
As far as I understand, it runs the first time but fails to call itself again...
$Childrenvariable not empty. VSCode with the PowerShell extension provides a really nice debugging experience.Display-OU -ParentOU $Parent -ChildOUs $Children. Despite confirming that both variables$Parentand$Childrenare populated.