Create AD Security Group/Distribution List from All SharePoint Users of the Farm
Have you ever had to send out an E-mail to all SharePoint users of your SharePoint Farm? Have you ever wanted to create a global AD security group that comprises all SharePoint users? Well, I’m sure, You will at some point in time. E.g., during scheduled maintenance, Grant access to a global site, etc. Your SharePoint farm may have multiple web applications with a lot of users accessing it. We can’t keep an AD group or distribution list in sync up to date with all SharePoint users, isn’t it? But we can create an AD security group or distribution list on-demand, which includes all users from the entire SharePoint farm. In this way, it will be more accurate and updated.
The idea is: Loop through each web application-site-collection-site in SharePoint farm to retrieve and add members to a security group or distribution list in AD.
PowerShell script to Add All SharePoint Users to an AD Security Group:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Import-Module ActiveDirectory
#Variables
$ADGroup="SP13 Authors" #Existing AD Security Group
$ReportPath="D:\SP13_Users.csv"
#Get all Webs from Entire FARM
$WebsCollection = Get-SPWebApplication | Get-SPSite -Limit All | Get-SPWeb -Limit All
#Array to hold user data
$UserDataCollection = @()
foreach($Web in $WebsCollection)
{
#Get all users from web programmatically
$UsersColl = $Web.AllUsers
#Get all users E-mails
foreach ($User in $UsersColl)
{
if( ($User.IsDomainGroup -eq $false) -and ($user.Email.ToString() -ne [string]::Empty))
{
$UserData = New-Object PSObject
$UserData | Add-Member -type NoteProperty -name "EmailID" -value $user.Email.ToString()
$UserDataCollection += $UserData
}
}
}
#Remove duplicates
$UserDataCollection = $UserDataCollection | sort-object -Property {$_.EmailID } -Unique
Write-host "Total Number of Unique Users found:"$UserDataCollection.Length
#Export to CSV
$UserDataCollection | Export-Csv -LiteralPath $ReportPath -NoTypeInformation
#Add each user to AD Group
$UserDataCollection | ForEach-Object {
#Get the user from Email id
$UserEmail = $_.EmailID
$ADuser = Get-ADUser -filter { EmailAddress -eq $UserEmail }
#Ignore Orphans
if($ADuser -ne $null)
{
#Add User to AD Aroup
Add-ADGroupMember -Identity $ADGroup -Members $ADuser
}
}
Run this script once. It will fetch and add all SharePoint users to the given AD group. To make it a distribution list, Head on to AD, Find and locate the AD Group, Go to its properties, assign an Email and change the Group type to “Distribution” if you need DL instead of Security group.