How to convert user field values into objects for adding permissions in powershell?
-
19-01-2021 - |
Question
I have a list with a multi select (user and group) field. I want to grab the values from there and then pass them to the add permissions method.
I grab the values but they come out like this
12;#Hanks, Tom 13;#Portal Visitors
How can I convert this into something that can be passed into the New-Object Microsoft.SharePoint.SPRoleAssignment
method so I can add their name to permissions, whether its a user or group?
If I try ensure user on Hanks, Tom
, won't that be an issue incase there are 2 people called Tom Hanks?
Thanks
Solution
The value from a multi-user field is actually a user object. You should be able to do the following to ensure the user from login name and add role assignments:
if (!(Add-PSSnapin microsoft.sharepoint.powershell -EA SilentlyContinue)) {
Add-PSSnapin microsoft.sharepoint.powershell -EA SilentlyContinue
}
# get web
$web = Get-SPWeb http://myintranet
# get role def
$role = $web.RoleDefinitions["Contribute"]
# get list
$list = $web.Lists["MyList"]
# get item
$item = $list.GetItemById(1)
# get MultiUser field 'PermUsers' value
$item["PermUsers"] | ForEach-Object {
# ensure user exists OR get group
if ($_.User) {
$user = $web.EnsureUser($_.User.UserLogin)
} else {
$user = $web.SiteGroups[$_.LookupValue]
}
# add assignment for user
$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($user)
# add role for assignment
$assignment.RoleDefinitionBindings.Add($role)
# add assignment to list
$list.RoleAssignments.Add($assignment)
}
# update list
$list.Update()
# dispose web
$web.Dispose()
Hope this helps!
Updated to work with both Users and SharePoint Groups.