Delete Folders, Sub-Folders from SharePoint Library using PowerShell

I need to delete a Folder from SharePoint document library using PowerShell programmatically.

PowerShell script to delete a folder in SharePoint:

To delete a Sub-folder from SharePoint Document Library using PowerShell:

 
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$siteURL = "https://sharepoint.crescent.com/sites/sales"
$listName = "Documents"
$folderToDelete = "v2"
  
#Get the Web
$web = Get-SPWeb $siteURL  
  
#Get all Sub folders
$folders = $web.Folders[$listName].SubFolders

Foreach ($folder in $folders)
{
    if ($folder.Name -match $folderToDelete)
    {
        $web.Folders[$listName].SubFolders.Delete($folder);
        Write-Host "Folder has been deleted!"
    } 
}

PowerShell to Delete Folder in SharePoint by URL:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Web
$Web = Get-SPWeb "https://intranet.crescent.com/sales"
$FolderRetiveURL = "/sales/Documents/Active/2017"

#Get the folder
$Folder = $web.GetFolder($FolderRetiveURL)
If ($Folder.Exists)
{
    $Folder.Delete() | Out-Null
    Write-host -f Green "Folder Deleted Successfully!"
}
Else
{
    Write-host -f Yellow "Could not find Folder at $FolderRetiveURL!"
}    

Delete All Folders from a Library:
Here is the PowerShell to delete all folders from a SharePoint library.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$siteURL = "https://sharepoint.crescent.com/sites/sales"
$listName = "Documents"
  
#Get the Web
$web = Get-SPWeb $siteURL  
  
#Get the list
$list = $web.lists[$listName]
  
#Get all folders under the list
$query =  New-Object Microsoft.SharePoint.SPQuery
$camlQuery = '<Where><Eq><FieldRef Name="ContentType" /><Value Type="Text">Folder</Value></Eq></Where>'

$query.Query = $camlQuery
$query.ViewAttributes = "Scope='RecursiveAll'"
$folders = $list.GetItems($query)

for ($index = $folders.Count - 1; $index -ge 0; $index--)
{
     Write-Host("Deleting folder: $($folders[$index].Name) at $($folders[$index].URL)")
     $folders.Delete($index);
}

Related Post: Create Folders and Sub-Folders in SharePoint Programmatically

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *