Adding users and claims to a site from PowerShell
Update: Astute readers will note that the following examples make use of the scratch custom claims provider.
Recently, the question of automating custom claim assignments to SharePoint groups has come up. For example, if you’ve got a custom claim provider that provides a custom claim of type http://schemas.bryanporter.com/favoriteColor, how could you add all users that present that claim to your farm into the Visitors group of a SharePoint site?
Managing users is pretty straightforward. So, if you had a user CONTOSO\brporter that already existed in a SharePoint site, you could simple run the following PowerShell to add them to the site and assign them to the Team Site Visitors group:
If your user was new to the site, replace Get-SPUser with New-SPUser and you are all set:
But what about a claim? What if you only want to allow users that present, say, a favoriteColor claim with a value of Blue to be able to visit a particular site? To make sure that ardent adorers of the color Blue can visit your site:
The non-obvious bit here is that we continue to deal with New-SPUser, even when we’re actually talking about a custom claim.
I should also point out that unless your custom claim provider successfully resolves the claim value and type you won’t get a claim reference that can return a proper encoded string – effectively preventing you from securing on the claim. For more infromation on implementing claim resolution, see Steve Peschka’s most excellent walkthrough on MSDN.
Good read.
I was wondering if you could help write a similar script to get a list of all users in the web application and/or site collection and add them to a particular SharePoint group in that web application and/or site collection?
Thanks.
When I tried this, I got a null value back for $claim.ToEncodedString()
Any idea why?
Here is what I did:
# The following line worked
$claimProvider = Get-SPClaimProvider | where { $_.DisplayName -eq "Forms Auth"}
# The following line worked
$claim = New-SPClaimsPrincipal -ClaimValue my@emailaddress.com -ClaimType I -ClaimProvider $claimProvider.ClaimProvider
# The following line shows the claim info
$claim
# Which returns the following (so I know it’s not null)
# ClaimType Value ValueType OriginalIssuer
# ——— —– ——— ————–
# I my@email… http://ww.w3… ClaimProvider:Forms
# But then the following line returns null
$claim.ToEncodedString()
# So, of course the next line in your example:
# $user = New-SPUser -UserAlias $claim.ToEncodedString() -Web http://<web site URL>
# returns an error