Public/Get-ADDirectReports.ps1
<#
.SYNOPSIS Retrieves direct reports for a given manager from Active Directory, optionally excluding those with a job title containing "System". .DESCRIPTION This function queries Active Directory to find the direct reports of a specified manager account. It includes an optional switch to exclude any direct reports whose job title contains the word "System". .PARAMETER sAMAccountName The sAMAccountName of the manager. .PARAMETER Continent The continent used to filter the direct reports. .PARAMETER ExcludeJobTitle If enabled, excludes direct reports whose job title contains the word "System". .PARAMETER ExcludeManager If enabled, Includes direct reports whose job title contains the word "System". .PARAMETER OnlyIT If enabled, Includes direct reports whose department is "Infrastructure Svcs". .EXAMPLE Get-ADDirectReports -sAMAccountName "test" -Continent "Asia" Retrieves direct reports for the manager 'test' who are located in Asia. .EXAMPLE Get-ADDirectReports -sAMAccountName "test" -Continent "Asia" -ExcludeJobTitle Retrieves direct reports for the manager 'test' who are located in Asia and excludes those whose job title contains "System". .NOTES Requires Active Directory module and appropriate permissions to read Active Directory objects. #> Function Get-ADDirectReports { [CmdletBinding()] param( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string]$sAMAccountName, [Parameter()] [string]$Continent = "Asia", [Parameter()] [switch]$ExcludeJobTitle, [Parameter()] [switch]$ExcludeManager, [Parameter()] [switch]$OnlyIT ) process { try { $strFilter = "(&(objectCategory=User)(sAMAccountName=$sAMAccountName))" $rootDSE = [ADSI]"LDAP://RootDSE" $domain = $rootDSE.Get("rootDomainNamingContext") $searcher = New-Object System.DirectoryServices.DirectorySearcher("GC://$domain") $searcher.PageSize = 1000 $searcher.Filter = $strFilter $searcher.SearchScope = "Subtree" $managerResult = $searcher.FindOne() if ($null -ne $managerResult) { $managerDN = $managerResult.Properties.distinguishedname[0] $reportsFilter = "(&(objectCategory=person)(objectClass=user)(manager=$managerDN))" if ($ExcludeJobTitle) { $reportsFilter ="(&(objectCategory=person)(objectClass=user)(manager=$managerDN)(!(ppdjobname=*System*)))" } if ($ExcludeManager) { $reportsFilter ="(&(objectCategory=person)(objectClass=user)(manager=$managerDN)(ppdjobname=*System*))" } if ($OnlyIT) { $reportsFilter ="(&(objectCategory=person)(objectClass=user)(manager=$managerDN)(department=*Infrastructure Svcs*))" } $searcher.Filter = "$reportsFilter" $reports = $searcher.FindAll() foreach ($report in $reports) { if ($report.Properties["extensionattribute2"] -match $Continent) { [PSCustomObject]@{ Name = $report.Properties["cn"][0] SamAccountName = $report.Properties["SamAccountname"][0] } } } } else { Write-Warning "Manager with sAMAccountName '$sAMAccountName' not found." } } catch { Write-Error "Error retrieving direct reports: $_" } } } |