Thursday, December 19, 2013

Purge huge list/library through PowerShell script quickly

If there are less than 20,000 items in the list, you can run the script below directly.

If there are more than 20,000 items......well, you can call the function multiple times :-)

Please let me know if you think there is a quicker way to clean up huge list.


Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue" 

$WebUrl = "http://server/sites/site1/web1" 

$web = Get-SPWeb -Identity $WebUrl 

function PurgeLargeList([string]$ListName) 

    $list = $web.Lists[$ListName] 

    if ($list -ne $null) 
    {
        $spQuery = New-Object Microsoft.SharePoint.SPQuery
        $spQuery.RowLimit = 20000
        $spQuery.ViewFields = ""
        $spQuery.ViewFieldsOnly = $true
        $spQuery.ViewAttributes = "Scope='Recursive'"
        $spQuery.Query = "0"
        $items = $list.GetItems($spQuery)
        $myArrayList = New-object System.Collections.Generic.List[int]
        
        foreach($item in $items)
        {
            Write-Host -NoNewline ".";
            $myArrayList.add($item.ID)
        }   

        $arraycount = $myArrayList.Count;
        for ($i = 0; $i -lt $arraycount; $i++)
        {
            Write-Host "Deleting " myArrayList[$i] $myArrayList[$i]
            $list.GetItemById($myArrayList[$i]).Delete()
        }
        
        $myArrayList.Clear()
        
        foreach ($folder in $list.Folders)
        {
            Write-Host -NoNewline ".";
            $myArrayList.add($folder.ID)
        }
        Write-Host " -> complete.";
        
        $arraycount = $myArrayList.Count;
        $folders = $list.Folders
        for ($i = 0; $i -lt $arraycount; $i++)
        {
            try {
                Write-Host -NoNewline "Deleting folder, ID: " $myArrayList[$i] " -> "
                $folders.DeleteItemById($myArrayList[$i])
            }
            catch {
                Write-Host "fail." -foregroundcolor "Red"
            }
            Write-Host "succ."
        }
        
        $myArrayList.Clear()
    } 


PurgeLargeList "list title" 

$web.Dispose() 

Write-Host "Completed.  Any key to exit..." 
Read-Host 

No comments:

Post a Comment