Get L2 manager in AD
If you want to use Active Directory to store the attribute for each user, of the level 2 manager (probably "director"), you can get this value programmatically. Some assumptions include that you populate the manager attribute of each user, and that the top-level (CEO) is listed as the manager of himself. The logic of course can be manipulated for whatever your situation is. I wrote this function which returns the L2 (or any other level you want) of the user. I leave it as an exercise for the reader to then plug this in to a ldap attribute.
Function Get-Level-Down-Manager {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True )][ValidateNotNullOrEmpty()]$User,
[Parameter(Mandatory=$False)][ValidateNotNullOrEmpty()]$Level = 2,
[Parameter(Mandatory=$False)][ValidateNotNullOrEmpty()]$Property = "Object",
[Parameter(Mandatory=$False)][boolean]$ShowStack = $False
)
Begin { $Stack = @() ; }
Process {
Try {
$thisUser = Get-ADUser $User -properties manager
Write-Verbose "$($thisUser)"
$Stack += $thisUser
}
Catch { Throw "Invalid user $User. Aborted" }
$done = $False
While (!$done) {
If ($ShowStack) { Write-Host $Stack }
$newUser = Get-ADUser ( Get-ADUser $thisUser -properties samaccountname,manager,userprincipalname ).manager -properties samaccountname,manager,userprincipalname
Write-Verbose "$($newUser)"
Try { $newUser = Get-ADUser $newUser -properties manager }
Catch { $LevelDownManager = $newUser ; $done = $True }
If ($newUser.userprincipalname -eq $thisUser.userprincipalname) {
# if person is the manager for self (so defined for the CEO, at least in AD) we are done.
$done = $True
$LevelDownManager = $Stack[-$Level]
} Else {
$Stack += $newUser
$thisUser = $newUser
}
}
# so now that we are done
If ($Property -ne "Object") {
$LevelDownManager = ( Get-ADUser $LevelDownManager -properties $Property ).$($Property)
}
Return $LevelDownManager
}
}
Comments