PowerShell Script to delete all files and folders in SharePoint Document library

Introduction

In this blog we will about to clean up the document library in SharePoint 2013 using PowerShell method. We need to delete all files and folders in document library in our Site Collection for our development purpose.

For that I have created a small PowerShell script to work on this.

Steps

  1. Start your windows PowerShell on your computer.
  2. Right click and select Run as administrator option.
  3. Paste the below script on the PowerShell window and click the enter button.
  4. Check your SharePoint site page will be created successfully.

Script

  1. Add-PSSnapin Microsoft.SharePoint.PowerShell    
  2.     
  3. $web = Get-SPWeb -Identity "http://thegowtham.sharepoint.com"    
  4.     
  5. $listname = $web.GetList("http://thegowtham.sharepoint.com /Library")    
  6.     
  7. function DeleteFiles   
  8. {    
  9.   param($folderUrl)    
  10.   $folder = $web.GetFolder($folderUrl)      
  11.   foreach ($file in $folder.Files)   
  12.   {    
  13.     # Delete file by deleting parent SPListItem    
  14.     Write-Host("DELETED FILE: " + $file.name)    
  15.     $list.Items.DeleteItemById($file.Item.Id)    
  16.   }    
  17.     
  18. }    
  19.   
  20. # Delete root files    
  21.     
  22. DeleteFiles($listname.RootFolder.Url)    
  23.   
  24. # Delete files in folders    
  25.     
  26. foreach ($folder in $listname.Folders)   
  27. {    
  28.   DeleteFiles($folder.Url)    
  29. }    
  30.   
  31. # Delete folders    
  32.     
  33. foreach ($folder in $list.Folders)   
  34. {    
  35.   try   
  36.   {  
  37.     Write-Host("DELETED FOLDER: " + $folder.name)    
  38.     $list.Folders.DeleteItemById($folder.ID)    
  39.   }    
  40.   catch   
  41.   {  
  42.     Write-Host(“Deletion of parent folder already deleted this folder”)    
  43.   }    
  44. }    

Run the script with the required administrator privilege.

To verify that, go the Pages Library and make sure that new page available or not.

Ebook Download
View all
Learn
View all