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

Run the script with the required administrator privilege.

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