How to delete a File from SharePoint Document Library using PowerShell?
Requirement: Delete a file from SharePoint document library using PowerShell
PowerShell to delete a file from document library:
At times, you may have to delete a particular file from a library. In one of my cases, as part of a deployment, before copying certain files, I had to check whether the particular file exists already in a document library, if yes, I must delete that particular file.
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
#Variables for processing
$WebURL = "https://intranet.crescent.com"
$ListName = "Documents"
$FileName="sharepoint databases v1.pptx"
#Get Web, List and List Item of the File
$Web = Get-SPWeb $WebURL
$List = $Web.Lists[$ListName]
$ListItem = $List.Items | Where {$_["Name"] -eq $FileName}
If($ListItem -ne $NULL)
{
#Delete the file
$ListItem.File.Delete()
Write-Host "File has been Deleted!" -f Green
}
else
{
Write-Host "File Not Found!" -f Yellow
}
How to Delete a file from URL using PowerShell?
Instead of file name, lets delete a file using its URL.
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
#Variables for processing
$WebURL = "https://intranet.crescent.com"
$FileRelativeURL="/Shared Documents/sharepoint databases v1.pptx"
Try {
#Get Web and File
$Web = Get-SPWeb $WebURL
$File = $Web.GetFile($FileRelativeURL)
If($File.Exists -eq $true)
{
#Delete the file using PowerShell
$File.Delete()
Write-Host "File has been Deleted!" -f Green
}
else
{
Write-Host "File Not Found!" -f Yellow
}
}
Catch {
write-host -f Red "Error deleting file !" $_.Exception.Message
}
An alternate approach to delete a document from SharePoint document library :
You can also delete a file using its Item ID. Here is how:
$List.Items.DeleteItemById($ListItem.Id)
This PowerShell script deletes file from library in SharePoint. Here is my another post: SharePoint Online: PowerShell CSOM to delete file