Skip to content
Amal Hashim
All posts
Snippet

PowerShell: import all AD users into a SharePoint 2010 group

A PowerShell script that finds every user in Active Directory, adds them to a SharePoint 2010 group and syncs their profile details.

1 min read#PowerShell#SharePoint 2010

Sometimes a SharePoint group needs to contain every user in the domain. Adding them by hand is slow, so this script reads all user accounts from Active Directory and adds each one to the group.

powershell
$spgroupname = "Group Name"
$sitename = "http://sitename"
$domain = $env:USERDOMAIN

$spsite = New-Object Microsoft.SharePoint.SPSite($sitename)
$rootweb = $spsite.RootWeb
$spgroup = $rootweb.Groups[$spgroupname]

$allowUnsafeUpdates = $spsite.AllowUnsafeUpdates
$spsite.AllowUnsafeUpdates = $true

$searcher = New-Object System.DirectoryServices.DirectorySearcher("(objectCategory=User)")
$results = $searcher.FindAll()
foreach ($result in $results) {
    $user = $result.GetDirectoryEntry()
    $username = $domain + "\" + $user.sAMAccountName
    $spsiteuser = $rootweb.EnsureUser($username)
    $spgroup.AddUser($spsiteuser)
}

$spsite.AllowUnsafeUpdates = $allowUnsafeUpdates

$rootweb.Dispose()
$spsite.Dispose()

Get-SPUser -Web $sitename | Set-SPUser -SyncFromAD

EnsureUser adds the account to the site if it is not there yet. The last line refreshes the user details from AD. Run the script from the SharePoint Management Shell.