Tuesday, March 4, 2014

Updating Permissions on List Items via PowerShell

The following script crawls all document libraries from a path of site and looks for *budget*.xls* and will replace all permissions on the Item with Read.
The script is useful to cut access for a pattern of files.

if ((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
 Add-PSSnapin Microsoft.SharePoint.PowerShell
}

$site = get-spsite -identity "http://myspportal"

foreach($web in $site.AllWebs)
    {

    if ($web.Url.Contains("http://myspportal/HR/"))     # Look for only under HR
        {

        $Lists = $web.Lists | Where-Object {$_.Title -Like "*Reports*"}   # Pattern to look for in LISTS names
        $roleReadOnly = $web.RoleDefinitions["Read"]

        foreach($list in $lists)
            {
            
             foreach($item in $list.Items | Where-Object {$_.Name -like "*budget*.xls*"})     # Filename pattern is *budget*.xls*
                {
                Write-Host $item.ParentList.ParentWeb.Url+'/'+$item.URL + '      ' + $item.Name
                if ($item.HasUniqueRoleAssignments -eq $false)
                    {
                    $item.BreakRoleInheritance($true);
                    }

                foreach ($ra in $item.RoleAssignments | Where-Object {$_.RoleDefinitionBindings.Name -eq "Contribute" -or $_.RoleDefinitionBindings.Name -eq "Full Control" -or $_.RoleDefinitionBindings.Name -eq "Edit"})
                    {
                        $ra.RoleDefinitionBindings.RemoveAll()
                        $ra.RoleDefinitionBindings.Add($roleReadOnly)
                        $ra.Update()
                    }

                }
            }
        }
    }

No comments:

Post a Comment