Microsoft 365 : SharePoint Online – PowerShell script to delete file using PnP PowerShell

Hi All,
Greetings for the day !!!
Today sharing one more PowerShell script – script to delete SharePoint online file using PnP PowerShell
Background / Use Case
- Our security team noticed that one important file is shared across multiple sites
- Our team has scanned and found all the sites and respective file locations
- CSV file is prepared
- Next our task is scan through CSV file, get the file location and delete the file
- So we have prepared the PowerShell script, we have used PnP PowerShell
Takeaway
- How to connect to PnP online using PowerShell
- At the end of this article we got to know how to delete respective file using PnP PowerShell
Prerequisites
- PnP online PowerShell module is installed
- If PnP online PowerShell module is not installed then please download latest PowerShell module and install
- You could install PowerShell PnP module using Install-Module CMDLET
Install-Module PnP.PowerShell
Details / Steps
- Connect to site using PnP PowerShell – using Connect-PnPOnline
#connect to PnP online - connect the site from which we need to delete the file
Connect-PnPOnline -Url https://knowledgejunction1.sharepoint.com/sites/Demo -Interactive
- Verify if file exists – using Get-PnPFile
#Verify if file exists
$file = Get-PnPFile -Url /sites/Demo/Shared%20Documents/fig1.png
if($file){
write-host "File exists"
}
- If file exists – delete the file. Here we are sending the file Recycle Bin using -Recycle parameter to CMDLET – Remove-PnPFile
- -Force attribute is used to bypass the dialog – file deletion confirmation
Remove-PnPFile -SiteRelativeUrl "/Shared Documents/fig1.png" -Recycle -Force
Complete Script
#import PnP PowerShell module
Import-Module PnP.PowerShell -DisableNameChecking
try{
#connect to PnP online - connect the site from which we need to delete the file
Connect-PnPOnline -Url https://knowledgejunction1.sharepoint.com/sites/Demo -Interactive
#Verify if file exists
$file = Get-PnPFile -Url "/sites/Demo/Shared Documents/backcover.jpg"
if($file){
#send file to recycle bin - using -Recycle parameter
Remove-PnPfile -SiteRelativeUrl "/Shared Documents/backcover.jpg" -Recycle -Force
Write-Host "File /sites/Demo/Shared%20Documents/backcover.jpg deleted
successfully" -ForegroundColor Green
}#if($file)
}#try
catch{
Write-Host "Exception occurred : $($_.Exception.Message)" -ForegroundColor Red
}#catch
References
- PnP PowerShell overview – https://learn.microsoft.com/en-us/powershell/sharepoint/sharepoint-pnp/sharepoint-pnp-cmdlets
- Connect-PnPOnline – https://pnp.github.io/powershell/cmdlets/Connect-PnPOnline.html
- https://knowledge-junction.in/category/technology-articles/powershell-cmdlets/