Below is a quick script I’ve been working on for a colleague. Its simple purpose is to query an AD group then display each member’s username and the email address of their manager. Hopefully this will help others accomplish this common task with ease.
(Update 04/11/2018)
I modified the script to include the employee’s full name and also to sort the output by that name. Additionally, the way I was handling the variable members and naming bothered me. I knew it could be better. So I did some more research and cleaned that up utilizing the -ExpandProperty option for select.
#################################################################################
#Script to pull the members of an AD group and display their manager's email.
#Author: Landon Fowler
#Date: 04/11/2018
#################################################################################
#Pull in the desired group name as a parameter
Param
( [Parameter(Mandatory=$True,Position=1)]
[string]$ADGroup )
#Import the necessary PowerShell module
Import-Module -DisableNameChecking -Name ActiveDirectory -Cmdlet Get-ADUser
#Create an empty object for display
$display = @()
#Get a list of the AD group members
$groupMembers = Get-ADGroupMember $ADGroup
#Loop through each user and add their username and manager's email to the display
foreach ($user in $groupMembers) { $manager = Get-ADUser $user -Properties
Manager | select -ExpandProperty Manager $objDisplay = New-Object System.Object
#Test whether the Manager field has a value, and if it does proceed
if ($manager)
{ $managerEml = Get-ADUser -Identity $manager -Properties emailaddress |
select -ExpandProperty emailaddress $objDisplay |
Add-Member -type NoteProperty -name EmployeeName -value $user.Name $objDisplay
| Add-Member -type NoteProperty -name Username -value $user.SamAccountName
$objDisplay | Add-Member -type NoteProperty -name ManagerEmail -value
$managerEml $display += $objDisplay
}
#If the manager field was empty or null, inform that no manager was present
else
{ $objDisplay | Add-Member -type NoteProperty -name EmployeeName -value
$user.Name $objDisplay | Add-Member -type NoteProperty -name Username -value
$user.SamAccountName $objDisplay | Add-Member -type NoteProperty -name
ManagerEmail -value "No Manager" $display += $objDisplay
} }
#Display the completed display object
$display | sort EmployeeName
Leave a Reply