It is possible to automate setting SharePoint Online document library permissions using the PowerShell SharePointPnPPowerShellOnline module. However in the module examples it is not clear how to add Azure Active Directory groups directly to list and document library permissions.
In this blog I will cover how to do this.
Firstly you will need the AzureAD PowerShell module https://docs.microsoft.com/en-us/powershell/azure/active-directory/install-adv2?view=azureadps-2.0
You will also need the SharePointPnPPowerShellOnline module https://github.com/SharePoint/PnP-PowerShell
Now lets set the variables we need to work with:
# Azure/O365 credentials used to get the Azure AD group info and set the SharePoint Online document library permissions $Credential = Get-Credential # Display name of the Azure AD group you wish to assign permissions to $Groupname = "Accounts Payable" # URL of your SharePoint Online site that contains the library $SiteURL = "https://mmageek.sharepointonline.com" # Document library name you will be assigning permissions to $LibraryName = "Accounts Documents"
To be able to assign the Azure AD group to the document library we need to get its object ID and assign it to a variable.
Connect-AzureAD -Credential $Credential # Get the ObjectId of your Azure AD group $GroupId = (Get-AzureADGroup -Filter "DisplayName eq '$GroupName'").ObjectId
Now we can connect to SharePoint Online to set the permissions
Connect-PnPOnline –Url $SiteURL –Credentials $Credential
If you want to break permissions inheritance on the library (optional)
Set-PnPList -Identity $LibraryName -BreakRoleInheritance
Now we can set the Azure AD group permissions on the library. Note that the roles available are Read, Contribute, Full Control.
Set-PnPListPermission -Identity $LibraryName -User "c:0t.c|tenant|$GroupId" -AddRole 'Contribute'
That’s it! now the Azure AD group has the permissions assigned to the library. If you wish to add the “Everyone except external users” group to the library you can use the following:
$AllExceptExternalUsers = Get-PnPUser | where-object title -eq "Everyone except external users" | Select-Object -expand loginname Set-PnPListPermission -Identity $LibraryName -User $AllExceptExternalUsers -AddRole "Read"
Here’s the full script: