Empty Library content on SharePoint Online PNP PowerShell script
This PNP PowerShell script we used to empty large SPO Libraries where the browser delete option does not work due to large number of files and folders stored in the library.
Below script uses Azure enterprise app authentication method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
$logfolder = "C:\EAppsCerts\" #Temp Directory $clientId = "id goes here" #ClientId $tenantId = "tenant id goes here" #Tenant ID $certPath = "C:\EAppsCerts\Pipe001.pfx" #Certificate Path $certPw = "cert password goes here" #Certificate Password $SiteURL1 = "https://lialis.sharepoint.com/sites/NotesA-ADMEA4" $logstring = "" cls Function LogWrite { Param ([string]$logstring) Add-content -Encoding UTF8 $Logfile -value $logString } filter timestamp {"$(Get-Date -Format G): $_"} $TimeStamp = (Get-Date).toString("dd/MM/yyyy HHmmssfff tt") Write-Host $TimeStamp $logfile = $logfolder + "Empty SP sites operation " + $TimeStamp + ".txt" $logExists = (Test-Path $logfile) if ($logExists) {clear-content $logfile} LogWrite $logStr write-host $("Start time " + (Get-Date)) LogWrite $("Start time " + (Get-Date)) Try { Connect-PnPOnline -Url $SiteURL1 -ClientId $clientId -CertificatePath $certPath -CertificatePassword (ConvertTo-SecureString -String $certPw -AsPlainText -Force) -Tenant $tenantId $siteLists = Get-PnPList | Where-Object {$_.Hidden -eq $false} foreach($list in $siteLists){ write-host $List.title $tenantListTitle = $list.Title if(($tenantListTitle -ne "Documents") -and ($tenantListTitle -ne "Events") -and ($tenantListTitle -ne "Form Templates") -and ($tenantListTitle -ne "Site Pages") -and ($tenantListTitle -ne "Style Library")) { write-host $List.title " - found Notes archive" #Get All Items from Folder in Batch $ListItems = Get-PnPListItem -List $List -PageSize 2000 | Sort-Object ID -Descending Write-host "Total Number of Items Found:"$ListItems.count #Powershell to delete all files from a folder ForEach ($Item in $ListItems) { Remove-PnPListItem -List $List -Identity $Item.Id -Recycle -Force Write-host "Removed Item:"$Item.FieldValues.FileRef Logwrite $("Removed Item:" + $SiteURL1 + $Item.FieldValues.FileRef) } } } } Catch { write-host "Error: $($_.Exception.Message)" -foregroundcolor Red LogWrite"Error: $($_.Exception.Message)" } write-host $("End time " + (Get-Date)) LogWrite $("End time " + (Get-Date)) |