PowerShell to Maintain a Line Managers Group

22 Mar

A simple bit of PowerShell (feel free to optimise it!) to scan AD for all users (that are enabled and have an email address set) and then assuming a group exists called “Line Managers” it will add anyone who has any direct reports into this group, and remove anyone that doesn’t.

$users = Get-ADUser -Filter {(displayName -notlike "_*") -and (enabled -eq "TRUE") -and (mail -like "*")} -Properties * |
select displayName, samaccountname, @{n='directReports';e={$_.directreports -join '; '}}

foreach ($item in $users){
if($item.directReports -ne ""){
#add to group
Add-ADGroupMember -Identity "Line Managers" -Member $item.samaccountname -confirm:$false
#remove from group
Remove-ADGroupMember -Identity "Line Managers" -Member $item.samaccountname -confirm:$false