Delete Library Content with Powershell

I have a process for our payroll department where I need to duplicate a SharePoint document library every month, keep the folder structure and permissions (permission set per folder) but remove all files.

I achieved this using ShareGate and Powershell. I use ShareGate to copy the library and keep the permissions intact

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Function to Delete all files in a Folder    
Function Delete-AllFilesFromLibrary([Microsoft.SharePoint.SPFolder]$Folder)
    #Delete All Files in the Folder
    Foreach ($File in @($Folder.Files))  
        #Recycle the file
        #$File.Recycle() | Out-Null

        #OR Delete skipping Recycle Bin
        $File.Delete() | Out-Null

        Write-host -f Green "Deleted File '$($File.Name)' from '$($File.ServerRelativeURL)'"
    #Delete files in Sub-folders
    Foreach ($SubFolder in $Folder.SubFolders | where {$_.Name -ne "Forms"})
        #Call the function recursively
#Get the Web and Library
$Web = Get-SPWeb "[YourSite]"
$Library = $Web.Lists.TryGetList("[List Name]")
#Call the function to Delete all files in the Library
Delete-AllFilesFromLibrary $Library.RootFolderTo remove all the files and keep the folders I run the Powershell script below

Leave a Reply

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