Public/Get-OrganizationalUnitsList.ps1
<#
.SYNOPSIS Retrieves a list of all organizational units (OUs) and sub-OUs within a specified base DN in Active Directory. .DESCRIPTION This function queries Active Directory to find all organizational units under the given distinguished name (DN). It outputs each OU's name and the distinguished name (DN) of the OU. .PARAMETER DN The Distinguished Name (DN) of the base organizational unit from which the search will start. This parameter is mandatory and accepts input from the pipeline. .EXAMPLE PS> Get-OrganizationalUnitsList -DN "DC=example,DC=com" This example retrieves all organizational units and sub-units starting from the domain "example.com". .OUTPUTS PSCustomObject Outputs each organizational unit's name and distinguished name. .NOTES Requires Active Directory module for PowerShell and appropriate permissions to query AD objects. #> function Get-OrganizationalUnitsList { [CmdletBinding()] [OutputType([PSCustomObject])] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string]$DN ) Begin { $dateTimeFormat = "[dd/MM/yy HH:mm:ss]" $dateTime = Get-Date -Format $dateTimeFormat $OU = "LDAP://$DN" Write-Verbose "Start time: $dateTime" Write-Verbose "Base OU: $OU" } Process { try { $searcher = [adsisearcher]"objectclass=organizationalunit" $searcher.SearchRoot = [ADSI]$OU $searcher.PropertiesToLoad.AddRange(@("adspath")) foreach ($entry in $searcher.FindAll()) { $adPath = $entry.Properties['adspath'][0] -replace 'LDAP://', '' [PSCustomObject]@{ OUName = $adPath DN = ($adPath.Split(",")[0]).Split("=")[1] } } } catch { Write-Error "Failed to retrieve organizational units: $_" } } End { Write-Verbose "Cleaning up resources..." Remove-Variable -Name searcher, OU, DN, dateTimeFormat, dateTime, adPath, entry -ErrorAction SilentlyContinue } } |