Adding users and managers departments to existing script

I have aa script that outputs user infomration from a collection of security groups. With assistance from this group, I was able to add the users’ Manager and manager email, as well as L2 Manager and L2 Manager email. Well, now I am now needing to include the user’s Department, as well as the L2 managers Department. I am still trying to learn the properties and how to extract that information. Any help is appreciated. I have included the section of the script I am using to extract what is currently working.

$AllMembers = foreach($ADGroup in $ADgroups) {
	#Get-ADGroupMember -Identity  $group | Select SamAccountName, Name, Manager
	Get-ADGroupMember -Identity  $ADgroup | Select -ExpandProperty DistinguishedName 
# Removes group names, duplicate IDs and adds manager
$AllMembersData = $AllMembers | Get-ADObject | ?{$_.objectclass -eq 'user'}

$Level1Managers = @{}
$Level2Managers = @{}

$NoManagerDetails = @{
    Name = 'N/A'
    Mail = 'N/A'

$UserDetails = foreach ($Member in $AllMembersData) {
   $User = Get-ADUser $Member -Properties Mail,Manager
   if ($User.Manager) {
       $L1Manager = $User.Manager
        if ($L1Manager -notin $Level1Managers.Keys) {
            $L1ManagerDetails = Get-ADUser $L1Manager -Properties Mail,Manager
        if ($Level1Managers.$($L1Manager).Manager) {
          $L2Manager = $Level1Managers.$($L1Manager).Manager
            if ($L2Manager -notin $Level2Managers.Keys) {
                $L2ManagerDetails = Get-ADUser $L2Manager -Properties Mail,Manager
        else {
            $L2Manager = 'NoManager'
    else {
        $L1Manager = 'NoManager'
        $L2Manager = 'NoManager'
    [PSCustomObject] @{
        Name           = $User.Name
        sAMAccountName = $User.SamAccountName
		Enabled		   = $User.Enabled
        Mail           = $User.Mail
        Manager        = $Level1Managers.$($L1Manager).Name
        ManagerEmail   = $Level1Managers.$($L1Manager).Mail
        L2Manager      = $Level2Managers.$($L2Manager).Name 
        L2ManagerEmail = $Level2Managers.$($L2Manager).Mail  

$UserDetailsUniq =  $UserDetails | Select-Object sAMAccountName, Name, Mail, Enabled, Manager, ManagerEmail, L2Manager, L2ManagerEmail,Department | Sort-Object -Property sAMAccountName -Unique

I’m not sure if I really got what your question is.

You simply add the department to the [PSCustomObject]. You have to add the property Department (or what the proper name is - I don’t have an AD at them moment to check) to the parameter -Properties of the cmdlet Get-AdUser to actually get the attribute included in the output of your query. But then it is the same as it is with the other attributes you’ve already included. :man_shrugging:t4:

The same is valid for the other attributes / properties you want to include for your managers.

1 Like

Thanks. Simply added the -Department to the properties.