Sunday, June 3, 2012

Powershell Script for Item Level permissions

Requirement: Have a large list (tens of thousands of items). Each List item has a unique set of permissions, assigned dynamically through a SPD workflow Activity at the time when the list item is added and the workflow kicked off. A new user arrives in the middle of the workflow approval process ( maybe a reorganization or a supervisor change), and that user needs to be assigned to all items with a certain common property (could range from 1 item to potentially 1000's of list items).


Solution: Need 2 powershell scripts, one that will take the itemId (if only 1 item needs to be reassigned) and reassign permissions, and the second that will take a View Name (if more than 1 item with a common property needs to be reassigned)/filter through a CAML Query and reassign permissions.


Script #1) Powershell script for reassignment of a large number of list item permissions, each sharing a common property that can be used to create a view/apply a filter is as follows:


You can get the CAML Query for the View or the filter and pass it as the Caml parameter:


The script takes in the following parameters:


- Url: Url of the Web that you want to run the script on.
- ListName: ListName of the List you want to run the script on
- Caml: Query to be passed into the script to apply the filter
- UserName: UserName of the user whose permissions need to be assigned to the List Item, for example: "domain\kevin"
- PermissionLevel: The permission level that needs to be assigned to the UserName on the List Item, for example: "Contribute"


   1:  #Load SharePoint Snap In
   2:  Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
   3:   
   4:  function Add-SPPermissionToListItemUserConditional
   5:  {
   6:   param ($Url, $ListName, $UserName, $Caml, $PermissionLevel)
   7:   $web = Get-SPWeb -Identity $Url
   8:   $list = $web.Lists.TryGetList($ListName)
   9:   if ($list -ne $null)
  10:   {
  11:          $spQuery = New-Object Microsoft.SharePoint.SPQuery        
  12:          $spQuery.Query = $Caml
  13:          $spQuery.RowLimit = 10000
  14:          $listItems = $list.GetItems($spQuery)        
  15:          $listItems.Count
  16:        foreach ($item in $listItems) 
  17:        {
  18:             if ($item.HasUniqueRoleAssignments -eq $False)
  19:             {
  20:              $item.BreakRoleInheritance($True)
  21:                  $user = $web.AllUsers[$UserName]
  22:                  $roleDefinition = $web.RoleDefinitions[$PermissionLevel]
  23:                  $roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($user)
  24:                  $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
  25:                  $item.RoleAssignments.Add($roleAssignment)
  26:                  $item.Update()
  27:                       Write-Host "Successfully added $PermissionLevel permission to $UserName in $ListName list. " -foregroundcolor Green
  28:             }
  29:             else
  30:             {
  31:                  $user = $web.AllUsers[$UserName]
  32:                  $roleDefinition = $web.RoleDefinitions[$PermissionLevel]
  33:                  $roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($user)
  34:                  $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
  35:                  $item.RoleAssignments.Add($roleAssignment)
  36:                  $item.Update()
  37:                       Write-Host "Successfully added $PermissionLevel permission to $UserName in $ListName list. " -foregroundcolor Green
  38:              }
  39:         }
  40:   }
  41:   
  42:   $web.Dispose()
  43:  }
  44:   
  45:  Usage: Add-SPPermissionToListItemUserConditional "Url" "ListName" "username" "<Where><Eq><FieldRef Name='Status' /><Value Type='Text'>Yes</Value></Eq></Where>" "PermissionLevel"




Script #2) Powershell script for reassignment of ONLY 1 list item permission is as follows:
The script takes in the following parameters:


- Url: Url of the Web that you want to run the script on.
- ListName: ListName of the List you want to run the script on
- ItemId: ID of the Item that needs to have the permissions reassigned upon
- UserName: UserName of the user whose permissions need to be assigned to the List Item, for example: "domain\kevin"
- PermissionLevel: The permission level that needs to be assigned to the UserName on the List Item, for example: "Contribute"




   1:  #Load SharePoint Snap In
   2:  Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
   3:  function Add-SPPermissionToListItemUser
   4:  {
   5:   param ($Url, $ListName, $ItemID, $UserName, $PermissionLevel)
   6:   $web = Get-SPWeb -Identity $Url
   7:   $list = $web.Lists.TryGetList($ListName)
   8:   if ($list -ne $null)
   9:   {
  10:    $item = $list.Items.GetItemByID($ItemID)
  11:     if ($item.HasUniqueRoleAssignments -eq $False)
  12:     {
  13:      $item.BreakRoleInheritance($True)
  14:          $user = $web.AllUsers[$UserName]
  15:          $roleDefinition = $web.RoleDefinitions[$PermissionLevel]
  16:          $roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($user)
  17:          $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
  18:          $item.RoleAssignments.Add($roleAssignment)
  19:          $item.Update()
  20:               Write-Host "Successfully added $PermissionLevel permission to $UserName in $ListName list. " -foregroundcolor Yellow
  21:     }
  22:         else
  23:         {
  24:             $user = $web.AllUsers[$UserName]
  25:          $roleDefinition = $web.RoleDefinitions[$PermissionLevel]
  26:          $roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($user)
  27:          $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
  28:          $item.RoleAssignments.Add($roleAssignment)
  29:          $item.Update()
  30:               Write-Host "Successfully added $PermissionLevel permission to $UserName in $ListName list. " -foregroundcolor Yellow
  31:         }
  32:    }
  33:   $web.Dispose()
  34:  }
  35:   
  36:   
  37:  Usage: Add-SPPermissionToListItemUser "Url" "ListName" "ID" "username" "permission level"

67 comments:

Anonymous said...

Nice post! I needed to break inheritance one some 11,000 Sharepoint folders. I used script #2 as a starting point. Had to change the delimeter to a colon since some of the items had a comma in the name. Also had to change 'items' to 'folders' in $list.items.GetItemByID($ItemID)since I was changing folders, not items. Your post was very helpful. Thanks!

MOHANA KRISHNA G said...

Hi Ashish,

I need to implement item level permissions for my form library,
Which contains multiple folders,
when i submit a form to a folder in the library,i need to set the permission of the folder to visible to only the people selected in a field of the infopath form.

can you please suggest me the way how can i achieve that

MOHANA KRISHNA G said...
This comment has been removed by the author.
Ashish said...

Mohana,

You can do this in several ways. You could use a SPD workflow which has an inbuilt activity that will allow you to break inheritance on that item and then set item level permissions. Or, you could do this through an Event REceiver upon submission of the form.

Unknown said...

Hi
I need to retrieve the permissions of each document item.
(to which item who are the users added and namely what permissions assigned)
help me...

Unknown said...

Hi Ashish,

Nice post. I tired this in 2010 and its working fine. But, when I tried this in SharePoint 2013 and I'm getting NULL value for
$user = $web.AllUsers[$UserName]
Could you please let me know if any changes required for SP 2013

Christopher said...

Good Day

Thanks for the good post.

I need some help here with the script, how can I set the permission to and item useing the current item field value?

Example: My doc lybriary has an column Memberlookup and I want to the the value of the column as the user.

Thanks, you help will be very helpfulll

Christopher

nikkolayebba said...

This web page is mostly a walk-via for all the info you wished about this and didn’t know who to ask. Glimpse here, and also you’ll undoubtedly uncover it. best online casino

Jerimiah thomas said...
This comment has been removed by the author.
Austin Green said...

You'll locate a range of bitcoin casinos that can be stable and also provably fair inside their company, on the reverse side, you'll find numerous imitation and unjust casinos that aren't stable. To learn more about bitcoin games, visit on hyperlinked site.

jenkins said...

Within this way, there's incredible benefit to urging people to bookmark your Web site. For more information on Kingpoker mobile read this.

Isabella Jackson said...

There is an increasing quantity of software providers. Get more interesting details about Live Casino genting on this site.

Isabella Jackson said...

There is an increasing quantity of software providers. Get more interesting details about Live Casino genting on this site.

oliver smith said...

If you are searching for the finest free spins no deposit bonuses, head to our home page and view the hottest offers from the largest and best casino brands on earth! You are curious to know more about slot machines, read this.

Austin Green said...

Vermont Powerball tickets might not be cancelled. The entrance fee might vary from challenge to challenge. If you are curious to know more about judi online, Read Me.

aliena dawid said...

Among the very many advantages of online gamblers is the fact that it is extremely convenient. If you are curious to know more about joker123, here you can get more information about it.

Valentino thomas said...

No, online sports betting isn't illegal in the usa. Author is an expert of sports betting, visit here for more interesting information.

Quenataucus Corner said...

Generally, slots have simple mechanics which don't ask for too much thinking. For more ideal details about live casino, pop over to these guys.

Valentino thomas said...

So there are numerous folks who'd love to be famous on social media to be in a position to run business and generate income. For more ideal details about live casino, pop over to these guys.

Valentino thomas said...

There are hundreds and hundreds of websites which provides online betting. For more information on roulette online, read me.

Smith Dsouza said...

When you play poker on the net, you can discover more about both. To learn more about agen idn poker, visit on hyperlinked site.

Valentino thomas said...

You do not demand traveling to a gambling enterprise to be able to delight in the game. For more ideal details about online gambling, pop over to these guys.

Smith Dsouza said...

It is considered the best game to learn how to maintain your focus for a long duration of time. Interested to know more about link idn poker? learn more.

Valentino thomas said...

This exciting new startup aims to get your bank transfer services over the internet and into your home for the first time. Click here to get more information about slot games.

Valentino thomas said...

It is very important to understand the type of play that you are doing when you play. For more ideal details about idnpoker, pop over to these guys.

TrevorCarlson said...

Regardless of how you view the real estate market, there is no better feeling than getting out of a house with no real intention of selling. You are curious to know more about online deposit, find out here.

WilliamsDamion said...

Every time your team loses, you make the bet. Likewise, if your team wins, you make the bet. If you want to see how much risk you're actually taking, you need to compare yourself to other people in the sport. You are curious to know more about sbobet88, browse this site.

kcretinasmithdcrouz said...

Sites which do not need any downloads can easily avoid getting a lot of reputation, and therefore they are the ones to look for. Want to know more about poker online? Discover here.

kcretinasmithdcrouz said...

The best sites offer many incentives and bonuses to help players that are new to the site or to a particular game get started. To learn more about online games, visit on hyperlinked site.

Valentino thomas said...

When you have selected the best online casino in Thailand, you are ready to start playing. For more ideal details about online casino games, pop over to these guys.

Valentino thomas said...

Their terms are often different from those of the sports book without NBA references, and they do their best to keep track of what is happening. Source for more about NBA over under betting.

Luna Harper said...

great website you have here. money lender singapore

legal money lender in bugis said...

wonderful website, please continue the updates!

moneylender near tanjong pagar said...

awesome website! love what you are doing here.

list of licensed money lender said...

love reading your website. very informative

license money lender near raffles place said...

keep up the good work that you are doing with this website! :)

Jessica world smith said...

Secondly, the user gets to play the games which are quite popular as well. There are a lot of different casino games available on Joker123 online casino games but not all of them are free. For more ideal details about baccarat csbetway recipe, pop over to these guys.

Jessica world smith said...

When one first thinks of online casino gaming, the first thing that comes to mind is a casino that offers no limits games. You may also find that you can earn some extra cash from these gaming website.

Smith Dsouza said...

So now that you know all of this you will have a better idea as to what you are looking for in terms of a happyluke login Casino website.

Valentino thomas said...

The game is so easy to play and anyone can find success if they do their homework well. Learn more about w88 casino online on this website.

Mackenzie Rodriguez said...

This means that you should always make sure that you only get the highest quality of gambling experience. To get more detailed info on agen bola, visit on hyperlinked site.

Alina Smith said...

That is why you should be very careful about trusting any online gambling website because many of them are actually scams. In this article I will show you how to distinguish between legit websites and those that are not so much.

Jessica world smith said...

Just like any other online gambling site, you need to know how to earn profits. The website that you choose to play at will be a big part of the success that you have with this. To get more detailed info on pkv poker, visit on hyperlinked site.

kcretinasmithdcrouz said...

Of course they will also try to make you win some money so you know that they will be happy for you to do so. The free of course will come with the site.

andriuwils said...

These games give you an opportunity to relax and enjoy the game in a virtual environment that has a feeling that is similar to the real casino. A lot of online casinos also allow you to win real money without spending a penny. Find out here to know more about w88 casino.

Valentino thomas said...

Gambling websites also offer bonus offers that can give you a nice return. For more ideal details about online casino website, pop over to these guys.

Jessica world smith said...

The data idn poker is a game that is very difficult to master, because it is very simple to get fooled by the computer and this is the number one thing that you have to watch out for when playing this game. To learn more about idn poker, visit on hyperlinked site.

Valentino thomas said...

Players can choose to play the traditional style of the game. Author is an expert of poker onlineqq, go here for more interesting information.

angelenaalessandro said...

If you are a newbie in the world of สูตรบาคาร่า, Online Baccarat Odds Calculator and you do not have a good amount of time to search for a free Baccarat Casino service that offers top notch casino gaming experience.

Hanry Taxton said...

In short, the Domino QQ Online Poker system is a great way to make money at home with poker, because it is a very simple system and all you have to do is get a hold of a Domino Poker Chips, a poker table, and a headset and you are all set. If you interested to know more about online gambling on this website.

Jessica world smith said...

It's very important to remember that a lot of online casinos charge fees for slots, so make sure to compare the rates and fees of each online casino before signing up. If you are curious to know more about situs judi slot, check here.

TrevorCarlson said...

Are you looking for a safe and reliable Baccarat Casino Site? If you are, then you have found the right place! It is my hope that this article will help you find the best Baccarat Casino Site. Source to know about 바카라사이트.

Jessica world smith said...

Casinos, betting rooms, sports book, and other gambling companies that operate online are sometimes referred to simply as online gambling sites, online gaming sites, or online gaming website.

Augustine Benjamin said...

As the name suggests, baccarat is one of the most exciting types of casino gambling that can be played. Not only does it involve the exciting game play itself, but the atmosphere of playing the game is also exhilarating. Click here to know more about sa game 666.

Jessica world smith said...

Most of the sites also provide an easy to use interface that makes the entire game more enjoyable to all the players. The various benefits of playing poker online.

TrevorCarlson said...

They offer an exciting chance to test your luck against another casino player, whilst helping you earn a little extra cash to spend at your favourite casinos. Want to know more about spin for real money? Find more information on this website.

hansal jackes said...

There are lots of different ways in which you can win a poker game and there are some strategies that work very well in this game. These poker hands ranking rules will allow you to find out here the exact strength.

Maria Garcia said...

Another part of this poker tracker software that you should consider is how it keeps track of everything that you do with your cards. Get more interesting details about poker software check out this site.

Alina Smith said...

To win the game, you must use the correct combination of drops of at least three candies. The drop colors are green, red, and yellow and if you mix these colors you will get either a high or a low quality drop. For more info about online slot, check out this site.

liamloyarsmith said...

Two players are seated in a round table or in a video poker machine to engage in an interactive game. One player may hold a card, while the other player may have nothing but a straight card. You are curious to know more about poker online, head over to the website.

geraldlewis said...

The different currency options that you can choose from include major world currencies such as US dollars, Japanese Yen, European Euros, and of course the dreaded British Pound. For more ideal details about online slot, visit this website.

Mike Chile said...

It is therefore very important for you to go through various tips and hints provided by these review articles so that you can select the most reliable sport betting safe site to place your bets. To learn more about 메이저사이트, visit on hyperlinked site.

geraldlewis said...

But while playing these games, it's important that you know what you're doing in order to ensure that you don't end up in debt and basically wasting time and effort only to be frustrated when you try to withdraw your winnings. Discover here for more information about game 168bet.

Smith Dsouza said...

This means that even if you are not online and only able to access the application through your PC, you are still able to interact with other users and discuss anything relevant to the latest PKV games. If you want to get more interesting details about pkv games, you may visit here.

Mike Chile said...

Once you know the expected value of each card online, it is easy to calculate and bet properly, since you already know what your chances of winning are.

Diego Walker said...

Some are also international, including the World Series of Poker. This book is popular in the United States and has a lot of followers, both because of its high quality games and the ease of use it offers. Learn more about 메이저토토 on this hyperlink site.

geraldlewis said...

In addition there is a one time membership fee for each user or client, which then allows them to play their choice of online games for free for a period of 10 days. You are curious to know more about online card games, head over to the website.