How to Delete a Subsite and All Lower Subsites using Powershell

Post date: Feb 28, 2014 5:18:11 PM

There are times when deleting sites from the UI can be tedious as you should delete from the bottom up. Not only that, depending on the size of the site, you may encounter an issue where you have exceeded your list threshold. So I decided to write a little bit of code that will get all the subsites from a user defined starting point and delete them one by one from the bottom up. Here is the code:

function Delete-SiteAndSubsites

{

Param

(

[parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][String]$StartWeb,

[Boolean]$IncludeStartWeb = $true

)

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get site and subsites starting at $StartWeb

$subsites = ((Get-SPWeb $StartWeb).Site).allwebs | ?{$_.url -like "$StartWeb*"}

#Reverse the order of the site array

[array]::Reverse($subsites)

#Traverse the array and delete each site

foreach($subsite in $subsites)

{

write-host "Deleting Site " $subsite.url

Remove-SPWeb $subsite.url -Confirm:$false

}

}

An alternative function to send the sites to the recycle bin (granted the two could be combined with a recycle switch):

function Recycle-SiteAndSubsites

{

Param

(

[parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][String]$StartWeb,

[Boolean]$IncludeStartWeb = $true

)

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get site and subsites starting at $StartWeb

$subsites = ((Get-SPWeb $StartWeb).Site).allwebs | ?{$_.url -like "$StartWeb*"}

#Reverse the order of the site array

[array]::Reverse($subsites)

#Traverse the array and delete each site

foreach($subsite in $subsites)

{

write-host "Recycling Site " $subsite.url

Remove-SPWeb $subsite.url -Confirm:$false -Recycle:$true

}

}

After you have stored this function, you can simply call it and pass to it the top site that you wish to delete. For Example, if I had a site structure that looked like:

And I wanted to delete the entire Alpha subsite and all of it's subsites, I would simply run the following command:

Delete-SiteAndSubsites -StartWeb "http://mysite.domain.com/alpha"

#-or-

Recycle-SiteAndSubsites -StartWeb "http://mysite.domain.com/alpha"