次の方法で共有


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 https://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:

 1 # If the user already exists in the site...
2 $user = Get-SPUser -Identity (New-SPClaimsPrincipal -Identity CONTOSO\brporter -IdentityType WindowsSamAccountName).ToEncodedString() -Web https://<web site URL>
3 Set-SPUser -Identity $user -Web https://<web site URL> -Group "Team Site Visitors"

If your user was new to the site, replace Get-SPUser with New-SPUser and you are all set:

 1 # If the user is new to the site
2 $user = New-SPUser -UserAlias (New-SPClaimsPrincipal -Identity CONTOSO\tuser -IdentityType WindowsSamAccountName).ToEncodedString() -Web https://<web site URL>
3 Set-SPUser -Identity $user -Web https://<web site URL> -Group "Team Site Visitors"

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:

 1 # If you are securing based on a claim
2 $claimProvider = Get-SPClaimProvider | where { $_.DisplayName -eq "The Name Of My Claim Provider"}
3 $claim = New-SPClaimsPrincipal -ClaimValue Blue -ClaimType https://schemas.bryanporter.com/favoriteColor -ClaimProvider $claimProvider.ClaimProvider
4 
5 $user = New-SPUser -UserAlias $claim.ToEncodedString() -Web https://<web site URL>
6 Set-SPUser -Identity $user -Web https://<web site URL> -Group "Team Site Visitors"

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.

Comments

  • Anonymous
    January 26, 2015
    What about an New FBA user creation. Is there any script to create a new FBA user in Sharepoint 2013?