SharePoint - Recursive delete SPWeb PowerShell script
Or, what happens when you stuffed up and need to clean up a lot of sites created by accident.
Story
- I have a feature receiver stapled to my site template, it checks a few conditions, does a few things, then creates 1 subsite and stops
- The new subsite is created, and runs the same receiver, it checks a few more conditions, does a few things. It shouldn't create any subsites.
- This afternoon, it did. The process did not stop.
- Ouch
Problem
- You can't delete the higher level web object when it has subsites. You can't follow the subsites because the path has gone way deep.
- Sounds like time for a good PowerShell script
Script
$web = get-spweb http://dev/ourprojects/nsw/1000
function CleanSite( $w )
{
$ws = $w.Webs;
foreach( $w1 in $ws)
{
CleanSite($w1)
}
echo $w.Title
$w.Delete()
}
CleanSite $web
Closing thoughts
My initial fears were that the feature receivers has gone berserk and I'd have hundreds of subsites to clean up. This turned out to be not the case - I only had about 12 subsites. I'm wondering if there was a SharePoint error that prevented deeper subsites from being created. So the disaster really wasn't that bad. 12 subsites I can manage.