Friday, August 2, 2019

Function that calls itself

This was an interesting function that I've come across.  It calls itself to work out the list of reports of a user and the reports of any of their reports from a particular AD arrangement where users' managers are held in a manager field.........! er yes, you can read that again now.



function Get-DirectReports([string] $Dn) {
    $Reports = Get-ADUser -LDAPFilter "(&(manager=$dn)(mail=*))" -Properties "mail", "title" -SearchBase "OU=EUC,DC=corp,DC=ad,DC=domain,DC=com"

    if ($Reports) {
        foreach ($Report in $Reports) {
                Write-Output $Report.DistinguishedName

            if ($Report.DistinguishedName -ne $Dn) {
                Get-DirectReports $Report.DistinguishedName
            }
        }
    }
}