I was trying to use PowerShell with a modern site (Communication site in my case) to save a list/library as a template and getting this error:
Having the UnauthorizedAccessException can be little confusing, so what’s the catch?
To solve this, we’ll use PowerShell, code looks like this:
Microsoft introduced prevented custom scripts from running by default in SharePoint online, and now with the introduction of modern sites in SharePoint 2019, they’re prevented by default in modern sites in SharePoint 2019. With custom scripts feature enabled, saving the site as a template and saving lists/libs as a template won’t be possible, hence you get the UnauthorizedAccess error. When custom scripts is active, the DenyPermissionsMask propert of the site collection will be: “AddAndCustomizePages” .. in order to allow custom scripts, it has to be “EmptyMask”.
You’ll need to run this command:
$site.DenyPermissionsMask = [Microsoft.SharePoint.SPBasePermissions]::EmptyMask
Now you can save the list/lib as a template.