Have you ever had to send out an E-mail to all SharePoint users of your SharePoint Farm? Ever wanted to create a global AD security group which comprises of all SharePoint users? Well, I'm sure, You will at some point of time. E.g. during scheduled maintenance, Grant access to a global site, etc. Your SharePoint farm may have multiple web applications with lot of users accessing it. We can't keep a AD group or distribution list in sync up to date with all SharePoint users, isn't it? But we can create a AD security group or distribution list on-demand which includes all users from the entire SharePoint farm. By this way, it will be more accurate and update.
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:
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 SilentlyContinueRun this script once. It will fetch and add all SharePoint users to the given AD group. To make it 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.
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 ""))
{
$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
}
}