Tuesday, 19 March 2013

Adding all users in an Active Directory group into a SharePoint group

Depending on what your strategy is for managing users in SharePoint groups, you might want to add all the users in an Active Directory group into a SharePoint group, without adding the actually Active Directory group itself.

Well, rather than adding them one at a time via the GUI (yawn), why not fire up PowerShell and tap out a few lines of code that will do it for you!

Before you do this, you need to have install RSAT and enabled the Active Directory module for PowerShell on one of your SharePoint servers.

Install RSAT (if you haven't already). Download it from Microsoft here: Remote Server Administration Tools

Once RSAT is install, open PowerShell and run the following command:
import-module ActiveDirectory

Now, the easy bit, run some code to add all the users from an Active Directory group into the SharePoint group.
$adGroupName = "my ad group";
$sharePointGroupName = "Home Members";
$sharePointWebUrl = "http://myweb/subweb";
$currentDomain = (Get-ADDomain).Name
$adGroupMembers = Get-ADGroupMember $adGroupName
$web = get-spweb $sharePointWebUrl
$sharePointGroup = $web.Groups[$sharePointGroupName]

foreach($u in $adGroupMembers){
$userInfo = Get-ADUser $u -Properties "mail"
$sharePointGroup.AddUser([String]::Format("{0}\{1}", $currentDomain, $userInfo.SamAccountName), $userInfo.mail, $u.name, $null);
Write-Host "Added user"$u.Name"to the"$sharePointGroup.Name"group" -foregroundcolor Green
} 



No comments:

Post a Comment