Forum Discussion
TJCooper
Aug 22, 2023Copper Contributor
Get AD Group Members, manipulate samAccountname, and then add to distribution list.
Hello everyone. I can do these 3 things separately but not as a script.
1. Query AD GroupMembers
2. Take the samAccountname and remove the first 3 digits
3. Lookup modified samAccountame and query for email address
4. Add email address to a DL
For example. Lets say a user has an account like SA-BondJames and is a member of a group "MI6". They also have an account called BondJames with an email address.
I want to query the group "MI6" for members, remove the "SA-" (special agent) then look up the BondJames (SA- removed) for an email address and then add that account/email to a DL.
Thank you
1 Reply
Sort By
- LainRobertsonSilver Contributor
Hi there.
I'm making some assumptions here as it's not entirely clear if you are talking about Active Directory and Exchange Server, Azure Active Directory and Exchange Online, some combination of the two (hybrid), or whether there's any write-back from Azure Active Directory to Active Directory (only relevant in a hybrid scenario.)
For the following example, I've made the assumption that you're talking about Active Directory and Exchange Server, but if you can provide some clarity on your environment, we can potentially provide a more appropriate example.
Example
$DistributionList = "Some Name"; Get-ADGroupMember -Identity "Domain Users" | Where-Object { # This is where we filter out anything that doesn't begin with the prefix we're interested in. ($_.objectClass -eq "user") -and ($_.sAMAccountName -like "SA-*"); } | ForEach-Object { $sAMAccountName = $_.sAMAccountName.Substring(3); if (($Results = Get-ADUser -Filter { (sAMAccountName -eq $sAMAccountName) -and (mail -like "*") } -Properties mail) -is [Microsoft.ActiveDirectory.Management.ADUser]) { # If we're in here, we received exactly one match. Add-DistributionGroupMember -Identity $DistributionList -Member ($Results.mail); } elseif ($Results -is [System.Object[]]) { # Outside of replication conflict scenarios, we should never end up in here. Write-Warning -Message "Searching on $sAMAccountName returned multiple matches."; } else { # If we're in here, nothing matched. Write-Warning -Message "Searching on $sAMAccountName returned no matches."; } }
Cheers,
Lain