SharePoint Online: Remove User or Group from Folder Permissions using PowerShell

Requirement: Remove user from folder permissions in SharePoint Online.

How to Remove user from folder permissions in SharePoint Online?
How to restrict access to folder in SharePoint Online? To remove a user or group from SharePoint Online Folder's permissions, follow these steps:
  • Navigate to your SharePoint Online list or library where the target folder is located. 
  • Click on "Details" from the specific Folder's context menu >> In the Details pane, Click on "Manage Access" and then "Advanced" links. This takes you to the "Advanced Permissions" page
  • From the ribbon, Click on "Stop Inhering Permissions" button and confirm the prompt.
    Remove Group from Folder Permissions
  • Now, You'll get the list of users and groups who have permissions on the folder. When you break the permission, SharePoint copies permissions from its parent (List/library in our case!) .
  • Select the users and groups you want to remove permission from folder and confirm the prompt.
    remove user from folder permissions powershell
  • That's all. We've removed user from folder permissions.
Remove User from folder permissions using PowerShell:
Here is my PowerShell to remove user permission from folder in SharePoint Online.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

Function Remove-SPOUserPermissionsFromList()
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $FolderURL,
        [Parameter(Mandatory=$true)] [string] $UserAccount
    )
 
    Try {
        #Get credentials to connect
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials
        $Web = $Ctx.web
 
        #Get the Folder
        $Folder = $Web.GetFolderByServerRelativeUrl($FolderURL)
        $Ctx.Load($Folder)
        $Ctx.ExecuteQuery()
     
        #Break Permission inheritence - Keep all existing list permissions & Don't keep Item level permissions
        $Folder.ListItemAllFields.BreakRoleInheritance($True,$False)
        $Ctx.ExecuteQuery()
        Write-host -f Yellow "Folder's Permission inheritance broken..."
      
        #Get the SharePoint User object from the site
        $User = $Web.EnsureUser($UserAccount)
        $Ctx.load($User)

        #Get permissions assigned to the folder
        $Ctx.Load($Folder.ListItemAllFields.RoleAssignments)
        $Ctx.ExecuteQuery()

        #Check if the user has permission on the list
        [Bool]$UserFound = $False
        ForEach($RoleAssignment in $Folder.ListItemAllFields.RoleAssignments)
        {
            $ctx.Load($RoleAssignment.Member)
            $Ctx.ExecuteQuery()

            #remove user permission from folder
            If($RoleAssignment.Member.LoginName -eq $User.LoginName)
            {
                $Folder.ListItemAllFields.RoleAssignments.GetByPrincipal($User).DeleteObject()
                $Ctx.ExecuteQuery()
                $UserFound = $True
                Write-host "User Permissions Removed from the List Successfully!" -ForegroundColor Green  
            }
        }
        #If user doesn't exist in list permissions
        If($UserFound -eq $False) { Write-host "User Not found in List Permissions!" -ForegroundColor Red}
    }
    Catch {
       write-host -f Red "Error Removing permissions from the Folder!" $_.Exception.Message
    }
}

#Config Variables
$SiteURL="https://crescent.sharepoint.com"
$FolderURL="/Project Docs/Active"
$UserAccount="[email protected]"

#Call the function to remove user permissions from a list
Remove-SPOUserPermissionsFromList -SiteURL $SiteURL -FolderURL $FolderURL -UserAccount $UserAccount
This PowerShell removes user from folder permissions on given parameters.

Remove Group from Folder Permissions using PowerShell
Similarly, to remove a SharePoint group from folder's permissions, use this PowerShell script.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

Function Remove-SPOGroupPermissionsFromList()
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $FolderURL,
        [Parameter(Mandatory=$true)] [string] $GroupName
    )
 
    Try {
        #Get credentials to connect
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials
        $Web = $Ctx.web
 
        #Get the Folder
        $Folder = $Web.GetFolderByServerRelativeUrl($FolderURL)
        $Ctx.Load($Folder)
        $Ctx.ExecuteQuery()
     
        #Break Permission inheritence - Keep all existing list permissions & Don't keep Item level permissions
        $Folder.ListItemAllFields.BreakRoleInheritance($True,$False)
        $Ctx.ExecuteQuery()
        Write-host -f Yellow "Folder's Permission inheritance broken..."
      
        #Get the SharePoint Site Group object
        $Group =$Web.SiteGroups.GetByName($GroupName)
        $Ctx.load($Group)

        #Get permissions assigned to the folder
        $Ctx.Load($Folder.ListItemAllFields.RoleAssignments)
        $Ctx.ExecuteQuery()

        #Check if the Group has permission on the list
        [Bool]$GroupFound = $False
        ForEach($RoleAssignment in $Folder.ListItemAllFields.RoleAssignments)
        {
            $ctx.Load($RoleAssignment.Member)
            $Ctx.ExecuteQuery()

            #remove Group permission from folder
            If($RoleAssignment.Member.LoginName -eq $Group.LoginName)
            {
                $Folder.ListItemAllFields.RoleAssignments.GetByPrincipal($Group).DeleteObject()
                $Ctx.ExecuteQuery()
                $GroupFound = $True
                Write-host "Group Permissions Removed from the List Successfully!" -ForegroundColor Green  
            }
        }
        #If Group doesn't exist in list permissions
        If($GroupFound -eq $False) { Write-host "Group Not found in List Permissions!" -ForegroundColor Red}
    }
    Catch {
       write-host -f Red "Error Removing Group permissions from the Folder!" $_.Exception.Message
    }
}

#Config Variables
$SiteURL="https://crescent.sharepoint.com"
$FolderURL="/Project Docs/Active"
$GroupName="Team Site Visitors"

#Call the function to remove Group permissions from a list
Remove-SPOGroupPermissionsFromList -SiteURL $SiteURL -FolderURL $FolderURL -GroupName $GroupName
This Removes SharePoint Online group from folder permissions using PowerShell. Here is my another post on granting permission to SharePoint Online Folder using PowerShell: Set Folder Permissions in SharePoint Online using PowerShell

PnP PowerShell to Remove User from Folder Permissions from a CSV file
We've a CSV file with list of URLs and wants to remove a particular user from all those folders. The CSV file has just one column with header "URL" and about 100+ rows in it.
#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/legal"
$ListName="Work"
$CSVFile = "C:\Temp\Folders.csv"
$UserAccount = "i:0#.f|membership|[email protected]"

Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -UseWebLogin

    #Get content from CSV file
    Import-Csv $CSVFile | ForEach-Object {
        Write-host "Processing Folder:"$_.URL
        #Get the Folder from URL
        $Folder = Get-PnPFolder -Url $_.URL

        #Get Folder Item
        $FolderItem = Get-PnPProperty -ClientObject $Folder -Property ListItemAllFields
        $HasUniquePerm =  Get-PnPProperty -ClientObject $FolderItem -Property HasUniqueRoleAssignments

        #Break Permission Inheritance
        If(!$HasUniquePerm)
        {
            $FolderItem.BreakRoleInheritance($True, $True)
            Write-host "`tFolder's Permission Inheritance Broken!"
        }
        #Get the User
        $User = Get-PnPUser -Identity $UserAccount -ErrorAction Stop

        #Get Permissions from the Folder
        $RoleAssignments = Get-PnPProperty -ClientObject $FolderItem -Property RoleAssignments

        #Remove user from folder permissions
        [Bool]$UserFound = $false
        ForEach($RoleAssignment in $RoleAssignments)
        {
           $Member =  Get-PnPProperty -ClientObject $RoleAssignment -Property Member
           If($Member.LoginName -eq $User.LoginName)
           {
                $UserFound = $True
                $FolderItem.RoleAssignments.GetByPrincipal($User).DeleteObject()
                Invoke-PnPQuery
           }
        }
        
        If($UserFound) { Write-host "`tRemoved user from Folder Permission!" }  
    }
}
Catch {
    write-host -f Red "Error Removing user from Folder:" $_.Exception.Message
}

1 comment:

Please Login and comment to get your questions answered!

Powered by Blogger.