Forum Discussion
Script to take accounts in security group with a prefixt, strip prefix, and add accounts to DL
I have a security group with accounts that are formatted with a prefix, such as AB-(sAMAccountName). I need to query the group (easy enough), then remove the first 3 characters in the string. Then use the resulting string (which is now sAMAccountName) to populate a DL. I can do all 3 things separately, but I cannot do them together.
I appreciate any help.
$users = Get-ADGroupMember -Identiy "Security Group" | Select-Object Name
Foreach ($user in $users) {
$sAMAccountName = $user.SubString(3)
Add-DistibutionGroupMember -Identity "group name" -Member $sAMAccountName
}
Am I close?
- LainRobertsonSilver Contributor
Hi, Theron.
Strictly-speaking, sAMAccountName cannot be used for the -Member parameter:
Your process could still work but it would be by accident rather than by good design.
Here's a very simple alternative where it's "good enough" if every user from your source security group is mail-enabled. Also, I'm assuming based on your example that you're working against Exchange Server and not Exchange Online (as this example won't work against the latter).
If the security group contains non mail-enabled users then this script isn't a great outcome since you'd receive an error for each non mail-enabled user. You'd need an entirely different script to avoid such errors.
Anyhow, it's a starting point for you to work from.
Get-ADGroupMember -Identity "Source security group" -Recursive | ForEach-Object { if ($_.objectClass -eq "user") { Add-DistributionGroupMember -Identity "Distribution list name" -Member $_.distinguishedName; } }
Cheers,
Lain