Adding Active Directory OU Members to a SharePoint 2013 Group

Over the last few months we've been busy writing the SharePoint 2013 developer courseware for Microsoft (check out 20488B and 20489B). That hasn't left much time for blogging, so I plan to write a few quick posts on some of the more tricky things we had to figure out along the way.

First up: how to use PowerShell to import a bunch of users from an Active Directory OU into SharePoint and add them to a group. The script below does the following:
  1. It adds a new group named Finance Members to the specified site.
  2. It links the group to the site as the associated members group.
  3. It grants the Contribute permission level to the group.
  4. It gets all the members of the Managers OU from Active Directory.
  5. It adds each AD user to the Finance Members group.

# Variables
$siteUrl = "http://finance.contoso.com"
$groupName = "Finance Members"
$groupDescription = "Members of this group can contribute to the Finance site."

# Load the SharePoint PowerShell snap-in
Write-Host "Loading SharePoint PowerShell snap-in..." 
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
Write-Host "Done"
Write-Host

Write-Host "Creating site members group..."
$web = Get-SPWeb $siteUrl
$web.SiteGroups.Add($groupName, $web.CurrentUser, $web.CurrentUser, $groupDescription)
$membersGroup = $web.SiteGroups[$groupName]
$web.AssociatedMembersGroup = $membersGroup

Write-Host "Granting contribute permissions to group..."
$membersGroupAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($membersGroup)
$membersRoleDef = $web.RoleDefinitions["Contribute"]
$membersGroupAssignment.RoleDefinitionBindings.Add($membersRoleDef)
$web.RoleAssignments.Add($membersGroupAssignment)
$membersGroup.Update()

Write-Host "Adding members of Managers OU to the SharePoint group..."
$adUsers = Get-ADUser -Filter * -Searchbase "OU=Managers,DC=contoso,DC=net"
foreach($adUser in $adUsers)
{
   Write-Host "...adding user $(adUser.UserPrincipalName) ..." -ForegroundColor Gray
   $user = $web.EnsureUser($adUser.UserPrincipalName)
   $membersGroup.AddUser($user)
}
$web.Update()
$web.Dispose()

Write-Host "Finished." -ForegroundColor Green

And there you have it. Essentially, we're using the SharePoint server-side object model to do most of the work, and the Get-ADUser cmdlet to get users from our AD OU. The Get-ADUser cmdlet provides a bunch of parameters for LDAP queries and the like, so check out the Get-ADUser documentation on TechNet if you want to get clever.

Comments

  1. There is so little online about AD OU and sharepoint. nice article.

    ReplyDelete
  2. There is so little online about AD OU and sharepoint. nice article.

    ReplyDelete

Post a Comment

Popular posts from this blog

Server-side activities have been updated

The target principal name is incorrect. Cannot generate SSPI context.

Custom Workflow Activity for Creating a SharePoint Site