Showing posts with label EnsureUser. Show all posts
Showing posts with label EnsureUser. Show all posts

Tuesday, March 15, 2016

Add users to SharePoint Group using PowerShell

Add users to SharePoint Group using PowerShell

I wanted to add bulk of users to a SharePoint group in a site collection.
I wrote the following PowerShell script to read a file with list of users and add them in a loop to a SharePoint group using Set-SPUser. There isn’t much description or documentation available on MSDN for this cmdlet, but it basically adds a user to a SharePoint site within a certain group.

$loc = Get-Location  
$Users = Get-Content "$loc\Data\Users.txt" 

foreach ($User in $Users) {  
 Set-SPUser -Identity $User -Web $siteCollUrl -Group $group   
}  
but here comes the surprise. Using Set-SPUser, I was not able to add all the users to the group and it gave the following error on most of the users.
You must specify a valid user object or user identity
t turns out to be that Set-SPUser can only set properties, permissions to a user account if it has already been added to SharePoint site. This means, you have to make sure that the user is already present in the SharePoint site. Otherwise, you can use the New-SPUSercmdlet to add the user. 
It just gets better. And I should be asked to bake a cake for anyone who is reading this blog as it was only while I writing this post I realized that it was even simpler and straight forward by using the EnsureUser.
SPWeb.EnsureUser checks whether the specified logon name belongs to a valid user of the website, and if the logon name does not already exist, adds it to the website.
In fact, EnsureUser does the same thing which I implemented myself in Solution 1 by using Get and New-SPUser.

$loc = Get-Location  
$Users = Get-Content "$loc\Data\Users.txt" 

$web = Get-SPWeb -identity $siteCollUrl
foreach ($User in $Users) { 
    $web.EnsureUser($User) 
    Set-SPUser -Identity $User -Web $siteCollUrl -Group $group  
} 
Hope this help,
oumaima


Sharepoint Designer 2013, XSLT List View Options ribbon option is not showing

Sharepoint Designer 2013, XSLT List View Options ribbon option is not showing I have an ordinary Wiki Page, also tried making an Article...