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 - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

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