2

Can anyone tell me the quickest way to delete a large number of documents from a site library if you are an administrator for the site? Any powershell commands?

9

Here is a PowerShell script to delete all the files and folders from a document library:

Add-PSSnapin Microsoft.SharePoint.PowerShell

$web = Get-SPWeb -Identity "http://sp2010srv"
$list = $web.GetList("http://sp2010srv/DocLib")

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
    }
}

I can't take full credit for this code; it was heavily adapted from Vedran Rasol's answer to this question.

5

I always end up using "Open in Windows Explorer", as that's quicker for me than trying to script something.

2

If speed of deletion is critical for you (you have really large amount of data), use batch operations. This post could be helpful for you, you can easily adopt it to the PowerShell Script. Batch operations are more fast, I think few times faster.

0

Use the list function ProcessBatchData(). Basically, you create an XML with all the items to delete and pass this XML to this function. It's faster than iterating over all the items and delete them one by one

function DeleteAllSPListItems
{
    param ([Microsoft.SharePoint.SPList] $spList_list );

    [System.Text.StringBuilder]$deleteBldr = New-Object "System.Text.StringBuilder";
    $deleteBldr.Append("<?xml version=""1.0"" encoding=""UTF-8""?><Batch>");
    $command = [System.String]::Format( "<Method><SetList Scope=""Request"">{0}</SetList><SetVar Name=""ID"">{1}</SetVar><SetVar Name=""Cmd"">Delete</SetVar></Method>", $spList_list.ID, "{0}" );

    foreach ($item in $spList_list.Items)
    {
        if($item -ne $null)
        {$deleteBldr.Append([System.String]::Format($command, $item.ID.ToString()));}
    }

    $deleteBldr.Append("</Batch>");

    $spWeb.ProcessBatchData($deleteBldr.ToString());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.