Deleting SharePoint Sub-Sites Recursively using PowerShell Script

SharePoint doesn’t allow us to delete the site if it has a sub-site inside it. Now think about a situation, if we have a long hierarchy of sub-sites in a site that we wanted to delete, then manually doing this task will take too much time. So, for such a kind of a scenario, I’ve created a PowerShell script that deletes the sub-sites recursively.

Below is the function that deletes the site recursively, by calling itself and deleting if it doesn’t have any children site.

function Delete-ChildWeb($ParentWeb){
    if
($ParentWeb.Webs.Count -eq 0 -and -not $ParentWeb.IsRootWeb){
    Write-Host
"Deleting Web '$ParentWeb'"

    $ParentWeb
.Delete()
    }

    else
{

        foreach
($childWeb in $ParentWeb.Webs){
        Delete-ChildWeb
$childWeb

    }
    if
(-not $ParentWeb.IsRootWeb){

        Write-Host
"Deleting Web '$ParentWeb'"
        $ParentWeb
.Delete()

     }
   }

}

The given below script is calling that function to delete the site,

$DeleteSiteCollection = $false
$SiteUrl
="http://spvm/"
if
($DeleteSiteCollection){
    Remove-SPSite
–Identity $SiteUrl –GradualDelete –Confirm:$False
}

else
{
    $Site
= Get-SPSite $SiteUrl

    $Web
= $Site.RootWeb
    Delete-ChildWeb
$Web
|
    Write-Host
"Web '$Web' deleted successfully" -ForegroundColor Green
}

If we set the value of the $DeleteSiteCollection object, as true, then it will delete the whole site collection from the content database.

Attached is the full powershell script.

Ebook Download
View all
Learn
View all