Skip to content

Instantly share code, notes, and snippets.

@joerodgers
Created October 18, 2017 15:24
Show Gist options
  • Save joerodgers/986a4ec97eda26b05a14033bfca24b83 to your computer and use it in GitHub Desktop.
Save joerodgers/986a4ec97eda26b05a14033bfca24b83 to your computer and use it in GitHub Desktop.
Add Users to a SharePoint Group in Bulk
function Add-UserToSharePointGroup
{
   param
(
[Parameter(Mandatory=$true)][Microsoft.SharePoint.SPWeb]$Web,
[Parameter(Mandatory=$true)][string]$SharePointGroupName,
[Parameter(Mandatory=$true)][string]$UserName
)
begin
{
}
process
{
$group = $web.SiteGroups | ? { $_.Name -eq $SharePointGroupName }
if( $group )
{
$userPrincipal = New-SPClaimsPrincipal -Identity $UserName -IdentityType WindowsSamAccountName
$spUser = $web.EnsureUser( $userPrincipal.ToEncodedString() )
if( $spUser )
{
$group.AddUser( $spUser )
}
else
{
Write-Error "User was not added to group: $UserName"
}
}
else
{
Write-Error "A SharePoint group with the name '$SharePointGroupName' was not found."
}
}
end
{
}
}
# get to the site
$web = Get-SPWeb -Identity "https://sharepoint.contoso.com/sites/teamsite"
# import the list of users
$users = Import-Csv -Path "C:\Users.csv"
foreach( $user in $users )
{
Add-UserToSharePointGroup -Web $web -SharePointGroupName "Team Site Members" -UserName $user.UserName
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment