Sunday, March 21, 2010

Deleting SharePoint lists with PowerShell

This web-scrapes the "All Site Content" page of a SharePoint site, picking out the Document Libraries and Lists that are not part of the default setup. It then deletes them (actually sends them to the recycle bin).

$cred = New-Object System.Management.Automation.PSCredential "domain\user",("pass" | ConvertTo-SecureString -AsPlainText -Force)

$client = new-object system.net.webclient
$client.Credentials = $cred

$page = $client.DownloadString("http://server/_layouts/viewlsts.aspx")
$matches = [regex]::Matches($page, "AllItems.aspx`">([^<]+?)<")

$toDel = $Matches | %{$_.groups[1].value} | ?{
$_ -ne "Customized Reports" -and
$_ -ne "Shared Documents" -and
$_ -ne "Site Assets" -and
$_ -ne "Style Library" -and
$_ -ne "Announcements" -and
$_ -ne "Links" -and
$_ -ne "Tasks" -and
$_ -ne "Team Discussion"}

$toDel | %{
$req = [System.Net.HttpWebRequest]::Create("http://server/$_")
#$req.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$req.Credentials = $cred
$req.Method = "DELETE"
$res = $req.GetResponse()

sleep 5 # give it a chance to catch its breath. otherwise, you may have to run the script several times
}


Emptying the recycle bin is left as an exercise to the reader (or me, when I have more time)

No comments: