Add users to SharePoint group from text CSV file with PowerShell
Once I had to add about 3 thousand users to SharePoint group. Usually when I have to add about 100 users, I use Excel function 'CONCATENATE' to add user login and ";" separator to generate a list of users. And then I manually enter them. But 3 thousand users – it's too much for manual.
Below I write down PowerShell script for SharePoint to add users to SharePoint group.
I have left comments in script for easier to find params for script. This script takes a text file with logins (each login on each line) and adds user to SharePoint group. As a result you'll have a log-file with statistics.
#PowerShell script to add users to SharePoint group from txt file if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin Microsoft.SharePoint.PowerShell } #set location for data files $loc = 'C:\Tools\SPScripts' #read array of string to $Users array from users.txt file $Users = Get-Content "$loc\users.txt" #set domain for users $domain = 'DomainName\' #set group name $groupName = 'Developers' #set location of log file $logFile = $loc + '\logfile.txt' $siteCollUrl = 'http://spdev/' $spwebUrl = $siteCollUrl + 'devsite/' $web = Get-SPWeb -identity $spwebUrl $group = $web.Groups | where {$_.Name -eq "$groupName" } Write-Host $group $header = "Adding users to $groupName" $header | Out-File $logFile $total = 0 $success = 0 $errors = 0 foreach ($User in $Users) { $total++ $domainUser = $domain + $User try { #If user is not in site collection, create SPUser $SPUser = $web.EnsureUser($domainUser) $group.AddUser($SPUser) $msg = "Success $User is added" $msg | Out-File $logFile -Append $success++ } catch { $errorMessage = "Error $User $_.Exception.Message" $errorMessage | Out-File $logFile -Append $errors++ } } $result = "---------------- Total: $total, Success: $success, Errors: $errors " Write-Host $result $result | Out-File $logFile -Append