30Aug/100
Sync a text file to an Exchange distribution group
Just a quick one for this bank holiday morning.
Here's a little bit of code that you can use to synchronise a text file with a list of recipient primary email addresses to a distribution group. A good use for it would be where you have exports from an application system to determine mailing lists that the users should be a member of, and want to keep the two in sync.
$File=Get-Content ".\testdg.txt"
$DG="testdg"
[array]$DGmembers=Get-DistributionGroupMember $DG
# Remove users who aren't in this group
if ($DGmembers.Count)
{
foreach ($i in $DGmembers)
{
if ($File -notcontains $i.PrimarySMTPAddress)
{
Write-Host "Removing $($i.PrimarySMTPAddress) from $($DG)"
Remove-DistributionGroupMember $DG -Member $i.PrimarySMTPAddress -Confirm:$false
}
}
}
# Add new members
foreach ($i in $File)
{
if (!($DGmembers | Where { $_.PrimarySMTPAddress -eq $i }))
{
if (Get-Recipient $i -ErrorAction SilentlyContinue)
{
Write-Host "Adding $($i) to $($DG)"
Add-DistributionGroupMember $DG -Member $i
} else {
Write-Host -f Red -b Black "Could not add $($i) to $($DG) - Recipient not found"
}
}
}
$DG="testdg"
[array]$DGmembers=Get-DistributionGroupMember $DG
# Remove users who aren't in this group
if ($DGmembers.Count)
{
foreach ($i in $DGmembers)
{
if ($File -notcontains $i.PrimarySMTPAddress)
{
Write-Host "Removing $($i.PrimarySMTPAddress) from $($DG)"
Remove-DistributionGroupMember $DG -Member $i.PrimarySMTPAddress -Confirm:$false
}
}
}
# Add new members
foreach ($i in $File)
{
if (!($DGmembers | Where { $_.PrimarySMTPAddress -eq $i }))
{
if (Get-Recipient $i -ErrorAction SilentlyContinue)
{
Write-Host "Adding $($i) to $($DG)"
Add-DistributionGroupMember $DG -Member $i
} else {
Write-Host -f Red -b Black "Could not add $($i) to $($DG) - Recipient not found"
}
}
}
The format of the input file is simply - just the primary email addresses, one per line.
Steve
Related posts:


