Wednesday 20 August 2014

Add users to SharePoint group using PowerShell to csv file

Below is the PowerShell code for adding user in SharePoint Group.

- Need to change some configure details in script.
- Need to chagne in CSV file like GroupName and UserID 

 
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue #Load Module
#Setvariable
#set the web application name
$varWebUrl="http://server-name/site/test/"
#set the CSV location, CSV format is [columnName(GroupName), columnName(UserID).
$varCSVLocation="C:\UserToUploadSharePointGroup\UserToUpload.csv"
#set the Log file location, where user details are save if not abel to add
$varLogFile="C:\UserToUploadSharePointGroup\UserNotAddedList.txt"
#------------------------------------------------------
$web = Get-SPWeb $varWebUrl
$count=1
$Time=Get-Date
Write-Host Start Time:$Time -ForegroundColor Yellow `n
# Import the .csv file, and specify manually the headers, without column name in the file
IMPORT-CSV $varCSVLocation |
  ForEach-Object {
    $group=$_.GroupName
    $user=$_.UserID
    $groupName = $web.SiteGroups[$group]
    Try
    {
        $user = $web.Site.RootWeb.EnsureUser($user)
        $groupName.AddUser($user)
        Write-Host -ForegroundColor green  ID:$count `t $user `t Users Added Successfully. 
    }
    Catch [system.exception]
    {
        Write-Host -ForegroundColor Red ID:$count `t $user `t Users is not added.
        $output= "ID:$count" +"  User: " +$user
        $output | Out-file $varLogFile -Append
    }
    $count=$count+1
  }
 $Web.Dispose()
 $EndTime = Get-Date
 Write-Host `n End Time:$EndTime -ForegroundColor Yellow
 

No comments:

Post a Comment