Programmatically "Apply Label To Items In List Or Library"

Introduction

 
This post explains how to apply a label at list/library level in SharePoint Online by using Client Side Object Model in PowerShell.
 
This script will help save us developers a lot of time in getting all the lists/libraries from a individual Site Colletion or subsites. So, here is the script.
  • Copy the below code to a .ps1 file.
  • Run the .ps1 file on the SharePoint PowerShell modules.
  • Configure the input parameters.
Source Code
  1. Add-Type -Path "xxxxx\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll"    
  2. Add-Type -Path "xxxxx\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll"    
  3. Add-Type -Path "xxxxx\Microsoft.Online.SharePoint.PowerShell\Microsoft.Online.SharePoint.Client.Tenant.dll"    
  4. #Set parameter values  
  5. $SiteURL="your site"  
  6. $LibraryName="Library Name"  
  7. $labelName=" your retension label name(Retain for 99 years)"  
  8. #Setup Credentials to connect  
  9. $Cred= Get-Credential  
  10. $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)  
  11. #Setup the context  
  12. $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)  
  13. $Ctx.Credentials = $Credentials  
  14. function GetSPODocLibraryFiles(){  
  15. param  
  16.     (  
  17.         [Parameter(Mandatory=$true)] [string] $SiteURL  
  18.          
  19.     )    
  20. try{  
  21.         $Web = $Ctx.Web  
  22.         $Ctx.Load($web)  
  23.         #Get all immediate subsites of the site  
  24.         $Ctx.Load($web.Webs)   
  25.         $Ctx.executeQuery()  
  26.         #Call the function to Get Lists of the web  
  27.         Write-host "Processing Web :"$Web.URL  
  28.         write-host -f White "Connected to Web";  
  29.         }  
  30.         catch  
  31.         {  
  32.           $Message= "Processing Web :$Web.URL $($_.Exception.Message)"   
  33.           Write-Log -Message $Message -Level ERROR  
  34.         }  
  35.         #Loop All the lists or libraries if you want to apply it for all otherwise get the perticular library  
  36.         $Lists = $Web.Lists   
  37.         $Ctx.Load($Lists)  
  38.         $Ctx.ExecuteQuery()  
  39.   
  40.         ForEach($Lib in $Lists)  
  41.         {  
  42.           #Get the List Name  
  43.         if($Lib | Where-Object { $_.BaseType -Eq "DocumentLibrary" })  
  44.          {  
  45.             Write-host $Lib.Title       
  46.             $Lib = $Ctx.Web.Lists.GetByTitle($LibraryName)  
  47.             $Ctx.Load($Lib)  
  48.             $Ctx.Load($Lib.RootFolder)  
  49.             $Ctx.ExecuteQuery()  
  50.   
  51.   
  52.         try  
  53.       {  
  54.   
  55.      $listId = $Lib.Id  
  56.      $ie = New-Object -com InternetExplorer.Application  
  57.     try  
  58.     {  
  59.         $applyLabelUrl = "$($Web.URL)/_layouts/15/Hold.aspx?Tag=true&List={$($listId)}"  
  60.         Write-Host $applyLabelUrl  
  61.         $ie.visible = $true  
  62.     
  63.         $ie.navigate($applyLabelUrl)  
  64.   
  65.         for ($i = 0; $i -lt 300; $i++)  
  66.         {   
  67.             if ($ie.ReadyState -eq 4) { break }  
  68.   
  69.   
  70.   
  71.             if ($i -eq 299) { throw "Unable to start IE session to simulate HP RM turning off inheritence." }  
  72.         }  
  73.         #Start-Sleep -Seconds 40  
  74.             $complianceTagDropDown = $ie.Document.getElementById('ctl00_PlaceHolderMain_inputFormSectionMain_ctl01_ComplianceTagDropDown')  
  75.   
  76.         for ($i = 1; $i -lt $complianceTagDropDown.options.length; $i++)  
  77.             {   
  78.                 if ($complianceTagDropDown.options[$i].text -eq $labelName)  
  79.                 {  
  80.                     $complianceTagDropDown.options[$i].selected = $true  
  81.                     $isFound = $true  
  82.                     break  
  83.                 }         
  84.             }  
  85.   
  86.         if ($complianceTagDropDown.id -ne "ctl00_PlaceHolderMain_inputFormSectionMain_ctl01_ComplianceTagDropDown")  
  87.         {  
  88.             throw "Didn't get assurance that I found complianceTagDropDown"  
  89.   
  90.         }  
  91.         else  
  92.         {  
  93.             $isFound = $false  
  94.             for ($i = 1; $i -lt $complianceTagDropDown.options.length; $i++)  
  95.             {   
  96.                 if ($complianceTagDropDown.options[$i].text -eq $labelName)  
  97.                 {  
  98.                     $complianceTagDropDown.options[$i].selected = $true  
  99.                     $isFound = $true  
  100.                     break  
  101.                 }         
  102.             }  
  103.   
  104.             if ($isFound -eq $false)  
  105.             {  
  106.                 throw "Unable to select '$($labelName)' in complianceTagDropDown. No such option?"  
  107.             }  
  108.             $checkMark=$ie.Document.getElementById('ctl00_PlaceHolderMain_inputFormSectionMain_ctl01_DefaultComplianceTagSyncToListItems')  
  109.             $checkMark.checked =$true  
  110.             $saveButton = $ie.Document.getElementByID('ctl00_PlaceHolderMain_ctl00_RptControls_btnOK')  
  111.             if ($saveButton.id -ne "ctl00_PlaceHolderMain_ctl00_RptControls_btnOK")  
  112.             {  
  113.                 throw "Didn't get assurance that I found saveButton"  
  114.             }  
  115.             else  
  116.             {  
  117.                 $saveButton.click()  
  118.             }  
  119.   
  120.         }  
  121.   
  122.     }  
  123.     finally  
  124.     {  
  125.         $ie.Parent.Quit()  
  126.         Start-Sleep 1  
  127.      }  
  128. }  
  129.   
  130. finally  
  131. {  
  132. }  
  133.   
  134. }  
  135. }  
  136.   
  137. }  
  138.   
  139. GetSPODocLibraryFiles -SiteURL $SiteURL  
Execute the program. Once it is executed successfully, you can see the label applied in the SharePoint List/Library.