PowerShell – add security permission levels NoDelete AddOnly

Sometimes I need to enable Contributor site access but with safety limitations.  “NoDelete” is the name I give for Contributor without Delete permissions.  “AddOnly” is the name I give for Contributor without Delete or Edit permissions.  Below is a quick PowerShell script “NoDeleteAddOnly.ps1” to create those permission levels.

UPDATE – Added SharePoint Online (CSOM)

# Credentials to connect to office 365 site collection url 
$url = "https://tenant.sharepoint.com/sites/team"
$username = "spadmin@tenant.onmicrosoft.com"
$password = "pass@word1"
$secPassword = $password | ConvertTo-SecureString -AsPlainText -Force
# Load CSOM
Write-Host "Load CSOM libraries" -Foregroundcolor Black -Backgroundcolor Yellow
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
Write-Host "CSOM libraries loaded successfully" -Foregroundcolor black -Backgroundcolor Green 
# Connect
Write-Host "Authenticate to SharePoint Online site collection $url and get ClientContext object" -Foregroundcolor black -Backgroundcolor yellow  
$context = New-Object Microsoft.SharePoint.Client.ClientContext($url) 
$cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $secPassword) 
$Context.Credentials = $cred
$context.RequestTimeOut = 1000 * 60 * 10
$web = $context.Web
$site = $context.Site 
$context.Load($web)
$context.Load($site)
try {
    $context.ExecuteQuery()
    Write-Host "Authenticated to SharePoint Online $url" -Foregroundcolor black -Backgroundcolor Green
}
catch {
    Write-Host "Not able to authenticate to SharePoint Online $url - $($_.Exception.Message)" -Foregroundcolor black -Backgroundcolor Red
    return
}
# Microsoft custom permission levels
# from https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.permissionkind.aspx
function CreateRoleDefinitions($permName, $permDescription, $clone, $addPermissionString, $removePermissionString) {
    $roleDefinitionCol = $web.RoleDefinitions
    $Context.Load($roleDefinitionCol)
    $Context.ExecuteQuery()
    # Check if the permission level is exists or not
    $permExists = $roleDefinitionCol |? {$_.Name -eq $permName}
    $clonePerm = $roleDefinitionCol |? {$_.Name -eq $clone}
    
    Write-Host Creating Pemission level with the name $permName  -Foregroundcolor black -Backgroundcolor Yellow
    if (!$permExists) {
        try {
            $spRoleDef = New-Object Microsoft.SharePoint.Client.RoleDefinitionCreationInformation
            $spBasePerm = New-Object Microsoft.SharePoint.Client.BasePermissions
			
            if ($clonePerm) {
                $spBasePerm = $clonePerm.BasePermissions
            }
            if ($addPermissionString) {
                $addPermissionString.split(",") | % { $spBasePerm.Set($_) }
            }
            if ($removePermissionString) {
                $removePermissionString.split(",") | % { $spBasePerm.Clear($_) }
            }
            $spRoleDef.Name = $permName
            $spRoleDef.Description = $permDescription
            $spRoleDef.BasePermissions = $spBasePerm    
            $web.RoleDefinitions.Add($spRoleDef)
            $Context.ExecuteQuery()
            Write-Host "Permission level with the name $permName created" -Foregroundcolor black -Backgroundcolor Green
        }
        catch {
            Write-Host "There was an error creating Permission Level $permName : Error details $($_.Exception.Message)" -Foregroundcolor black -backgroundcolor Red
        }
    }
    else {
        Write-Host "Permission level with the name $permName already exists" -Foregroundcolor black -Backgroundcolor Red
    }
}
 
# Create 4 Custom Permission Levels.  Defined by removed permission strings.
CreateRoleDefinitions -permName "NoDelete" -permDescription "Contribute - without Delete" -clone "Contribute" -removePermissionString "DeleteListItems"
CreateRoleDefinitions -permName "AddOnly" -permDescription "Contribute - without Edit or Delete" -clone "Contribute" -removePermissionString "DeleteListItems,EditListItems"
CreateRoleDefinitions -permName "NoEdit" -permDescription "Contribute - without Edit" -clone "Contribute" -removePermissionString "EditListItems"
CreateRoleDefinitions -permName "EditOnly" -permDescription "Contribute - without Edit" -clone "Contribute" -removePermissionString "AddListItems,DeleteListItems"

SharePoint On-Premise (SOM)

image

image

# #############################################################################
# NAME:		NoDeleteAddOnly
#
# AUTHOR:	Jeff Jones
# DATE:		09/13/2013
# EMAIL:	spjeff@spjeff.com
# WEBSITE:	www.spjeff.com
# TWiTTER:	@spjeff
#
# COMMENT:  This script creates two Custom Access levels for
#			a given SharePoint URL.
#
#			* NoDelete = Contribute without delete
#			* AddOnly = Contribute without delete or edit
#
# REQUIRE:  Permission to unlock account
# USAGE:    .\NoDeleteAddOnly.ps1 http://sharepoint/sites/team
#
# #############################################################################
[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True,Position=1)]
   [string]$url
)
Write-Host "Opening $url ... " -NoNewLine
$web = Get-SPWeb $url
Write-Host "OK" -ForegroundColor Green
$nd = $web.RoleDefinitions |? {$_.Name -eq "NoDelete"}
if ($nd) {
	Write-Host "Found NoDelete" -ForegroundColor Green
} else {
	Write-Host "Missing NoDelete" -NoNewLine
	Write-Host "Adding NoDelete ..." -NoNewLine
	$noDeleteRole = New-Object "Microsoft.SharePoint.SPRoleDefinition"
	$noDeleteRole.Name = "NoDelete"
	$noDeleteRole.Description = "This group can view, add, and edit items, but cannot delete items"
	$noDeleteRole.BasePermissions = "AddAndCustomizePages,AddDelPrivateWebParts,AddListItems,BrowseDirectories,BrowseUserInfo,CreateAlerts,EditListItems,EditMyUserInfo,ManagePersonalViews,Open,OpenItems,UpdatePersonalWebParts,UseClientIntegration,UseRemoteAPIs,ViewFormPages,ViewListItems,ViewPages,ViewVersions"
	$web.RoleDefinitions.Add($noDeleteRole)
	Write-Host "OK" -ForegroundColor Green
}
$ao = $web.RoleDefinitions |? {$_.Name -eq "AddOnly"}
if ($ao) {
	Write-Host "Found AddOnly" -ForegroundColor Green
} else {
	Write-Host "Missing AddOnly" -NoNewLine
	Write-Host "Adding AddOnly ..." -NoNewLine
	$addOnlyRole = New-Object "Microsoft.SharePoint.SPRoleDefinition"
	$addOnlyRole.Name = "AddOnly"
	$addOnlyRole.Description = "This group can view, add, and edit items, but cannot delete or edit items"
	$addOnlyRole.BasePermissions = "AddAndCustomizePages,AddDelPrivateWebParts,AddListItems,BrowseDirectories,BrowseUserInfo,CreateAlerts,EditMyUserInfo,ManagePersonalViews,Open,OpenItems,UpdatePersonalWebParts,UseClientIntegration,UseRemoteAPIs,ViewFormPages,ViewListItems,ViewPages,ViewVersions"
	$web.RoleDefinitions.Add($addOnlyRole)
	Write-Host "OK" -ForegroundColor Green
}



Return to Top ▲Return to Top ▲