Friday, September 23, 2011

How to Delete a SharePoint Site and All of It's Sub Sites

We were recently doing some maintenance cleaning up old sites when we noticed an annoying feature. When you try to delete a site that has numerous sub sites, SharePoint will continually kick out errors telling you it can't delete the current site because it has sub sites. This forces you to manually go through and delete the lower level sites, then work your way up.

I understand this is a "safety" feature to help make sure you don't delete any sub sites you didn't mean to, but I really want to get rid of this legacy site that's taking up a big chunk of SQL disk.

The solution? Run the following powershell command. Be sure you have a good backup in case you change your mind and substitute the site name (http://site/subsite) with the name of the sub site you want to nuke.

function RemoveSPWebRecursively(
  [Microsoft.SharePoint.SPWeb] $web)
{
Write-Debug "Removing site ($($web.Url))..."


$subwebs = $web.GetSubwebsForCurrentUser()


foreach($subweb in $subwebs)
{
RemoveSPWebRecursively($subweb)
$subweb.Dispose()
}

$DebugPreference = "SilentlyContinue"
Remove-SPWeb $web -Confirm:$false
$DebugPreference = "Continue"
}


$DebugPreference = "SilentlyContinue"
$web = Get-SPWeb "http://site/subsite"
$DebugPreference = "Continue"

If ($web -ne $null)
{
RemoveSPWebRecursively $web
$web.Dispose()
}