Having authenticated to a SharePoint online Site, Site Collection or a OneDrive site, like me, you may have the need to add retention labels to folders and the files within those folders. I have seen this done a lot using the SharePoint Online PowerShell Module but in terms of authentication in the modern world it is not so easy to authenticate to that module at site level.
So in steps the mega powerful PnP PowerShell. The method I will demonstrate below will use PnP to apply the retention label to both root Documents & Shared Documents and an alternative way to apply the labels to subfolders too.
Should you be looking to automate this process in bulk or are just looking for an easy way to authenticate without having to respond to MFA prompts. Please see Connect-PnPOnline Unattended Using Azure App-Only Tokens.
Set Retention Label on the Root Folder
$RootLabel = "Default" # SharePoint Online Set-PnPLabel -List "Shared Documents" -Label $RootLabel # OneDrive for Business Set-PnPLabel -List "Documents" -Label $RootLabel
If you look more closely at the documentation for Set-PnPLabel, you will notice it states "Sets a retention label on the specified list or library".
As a subfolder is not a list nor a library the command will not work even if you target "Shared Documents/My SubFolder". In fact it returns no feedabck and actually sets the label to the root folder, "Shared Documents".
In Order to achieve our desired result, see the below example where I firstly create a folder then apply a retention label.
Set Retention Label on a Subfolder
$Folder = "My Recipes" $Label = "Recipes" # SharePoint Online Add-PnPFolder -Name $Folder -Folder "Shared Documents" $Folder = Get-PnPFolder -Url "Shared Documents/$($Folder)" $Folder.ListItemAllFields.SetComplianceTagWithNoHold($Label) Invoke-PnPQuery # OneDrive for Business Add-PnPFolder -Name $Folder -Folder "Documents" $Folder = Get-PnPFolder -Url "Documents/$($Folder)" $Folder.ListItemAllFields.SetComplianceTagWithNoHold($Label) Invoke-PnPQuery
As you will see, the folder is created then the label applied. The files within the subfolder then inherit the label of their parent folder.
Thanks for reading.Tweet