Friday, December 2, 2016

Delete all files & folders from SharePoint library

Add-PSSnapin Microsoft.SharePoint.PowerShell

# Replace siteurl with actual web url
$web = Get-SPWeb -Identity "siteurl"
# Replace docurl with document library url
$list = $web.GetList("docurl")

function DeleteFiles {
    param($folderUrl)
    $folder = $web.GetFolder($folderUrl)
    foreach ($file in $folder.Files) {
        # Delete file by deleting parent SPListItem
        Write-Host("DELETED FILE: " + $file.name)
        $list.Items.DeleteItemById($file.Item.Id)
    }
}

# Delete root files
DeleteFiles($list.RootFolder.Url)

# Delete files in folders
foreach ($folder in $list.Folders) {
    DeleteFiles($folder.Url)
}

# Delete folders
foreach ($folder in $list.Folders) {
    try {
        Write-Host("DELETED FOLDER: " + $folder.name)
        $list.Folders.DeleteItemById($folder.ID)
    }
    catch {
        # Deletion of parent folder already deleted this folder
    }
}

No comments:

Post a Comment