SharePoint Online: Delete a Subsite using PowerShell

Requirement: SharePoint Online PowerShell to Remove a Subsite.

How to Delete a Subsite in SharePoint Online?

Is there a subsite in your SharePoint Online environment that is no longer needed? Maybe it was created by mistake or is no longer being used. If so, we can delete it and free up some storage space! In this blog post, I will show you the steps to remove a subsite and share some script examples of how to delete a subsite in SharePoint Online using PowerShell. This is a quick and easy way to clean up your environment and can be done in just a few minutes. Let’s get started!

Any user with Manage Hierarchy or Full Control permissions can delete the site in SharePoint Online when it’s no longer needed. To delete a subsite from SharePoint Online, do the following:

  1. Login to your SharePoint Online site >> Click on Site Settings gear >> Choose “Site Settings”.
  2. Click on the “Delete this site” link under the “Site Actions” group. (If you don’t see the “Delete this site” link, that means you don’t have permission to delete the site, or you are on a modern team site or communication site!)
    sharepoint online powershell delete subsite
  3. This leads you to the “Delete this site” page in classic sites. Click on the “Delete” button and confirm subsite deletion.
    delete a subsite sharepoint online
  4. And you’ll get a “Your Web site has been deleted.” message in a while.

SharePoint Online: How to delete a subsite?

Similarly, on a modern SharePoint site, You can click on “Settings” >> Site Information >> Delete Site.

delete site in shaerpoint online

Confirm the deletion by selecting the “Yes, delete this site and its associated content.” checkbox and then clicking on the “Delete” button. When you delete a site, you are also deleting all resources associated with the site, like any subsites, Site Settings, user information, site contents such as documents, document libraries, lists, and list data associated with the site.

Remove SharePoint Online Subsite using Sites and Workspaces

You can also use the “Sites and Workspaces” link to bulk remove subsites in SharePoint Online. Here is how:

  1. Navigate to the parent site which contains the subsite you want to delete.
  2. Click on Settings Gear >> Select Site Settings
  3. On the Site Settings page, under the Site Administration section, click on the “Sites and Workspaces” link.
  4. On the Sites and Workspaces page, click on the Delete icon next to the subsite to be deleted.
  5. Click the Delete button >> Click the OK button to confirm.
    sharepoint online delete subsite using sites and workspaces

This removes the subsite in SharePoint Online. Deleting all subsites in SharePoint Online is a daunting task. You can do it, but when you have a large number of subsites in Sharepoint Online, it can be cumbersome to delete them one by one. So, we will show how to delete subsite in SharePoint Online using PowerShell!

You need to have SharePoint Online Management Shell or CSOM SDK for SharePoint Online installed on your machine before executing these scripts. You can download it from here https://www.microsoft.com/en-in/download/details.aspx?id=35588

If you accidentally delete a subsite through the web user interface (NOT through PowerShell!), the site collection administrator can restore it from the site collection recycle bin.

Delete a subsite in SharePoint Online using PowerShell:

How to delete a subsite in SharePoint Online using PowerShell? Well, while removing subsites in SharePoint Online using web browser UI is relatively simpler, We may need PowerShell in some instances, such as:

  • When you have to delete subsites in bulk.
  • If you want to delete a sub-site that has its child-subsites (You’ll get this error: “There was a problem deleting Web site “/sites/Sales/apac”. Sites that have subsites or certain apps can’t be deleted. Please try again after deleting all subsites and removing the apps.”)

Here is the PowerShell to delete a subsite in SharePoint Online:

#Load SharePoint Online Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
   
#Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/sites/Marketing/townhall2019/"

Try{  
    #Get Credentials to connect
    $Cred= Get-Credential

    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password) 
    
    #Get the subsite to delete
    $web = $Ctx.Web
    $Ctx.Load($web)
    $Ctx.ExecuteQuery()

    #sharepoint online powershell remove subsite
    $web.DeleteObject()
    $Ctx.ExecuteQuery()

    Write-Host "Subsite Deleted:" $web.Title -foregroundcolor Green
}
Catch{
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

This PowerShell script removes the SharePoint Online Subsite. Please note, these methods permanently delete the subsite without sending them to Recycle bin (in other words, if subsites deleted through PowerShell can’t be recovered)

How to Delete All subsites under a Site in SharePoint Online using PowerShell?

Let’s wrap the above script into a reusable function to delete subsites recursively in a site collection!

#Load SharePoint Online Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
   
#Variables for Processing
$SiteUrl = "https://portal.sharepoint.com/sites/Sales/apac/us/"
$UserName="[email protected]"
$Password ="password goes here"

#Function to delete a subsite and its all child sites
Function Remove-SPOWeb() {
param(
    $WebURL = $(throw "Please Enter the Subsite URL to Remove:")
)
    try{
        #Setup Credentials to connect
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
  
        #Get Web information and subsites
        $Context = New-Object Microsoft.SharePoint.Client.ClientContext($webURL)
        $Context.Credentials = $credentials
        #get the subsite
        $web = $context.Web
        $context.Load($web)
        $Context.Load($web.Webs)
        $Context.executeQuery() 
 
        #Iterate through each subsite in the current web
        foreach ($Subweb in $web.Webs)
        {
            #Call the function recursively to process all subsites underneaththe current web
            Remove-SPOWeb($Subweb.url)
        }

        #sharepoint online powershell delete web
        $web.DeleteObject()
        $context.ExecuteQuery()
        Write-Host "SubSite Deleted:" $web.Title -foregroundcolor Green
        }
    catch{
        write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
    }
}
 
#Call the function to remove subsite
Remove-SPOWeb -WebURL $SiteUrl

This PowerShell deletes all subsites in SharePoint Online site. With just a few lines of code, you can save yourself a lot of time and hassle!

SharePoint Online PnP PowerShell to Remove Subsite

To delete a subsite in SharePoint Online using PnP PowerShell, use: Remove-PnPWeb PowerShell command. Here is how to delete subsite using PnP PowerShell:

#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/Sales"
$SubsiteURL = "2018" # Just URL of the Subsite under parent site - NOT Relative Path

#Get Credentials to connect
$Cred = Get-Credential
 
#Connect PnP Online to Parent Web
Connect-PnPOnline -Url $SiteURL -Credentials $Cred

#sharepoint online delete subsite powershell
Remove-PnPWeb -Url $SubsiteURL -Force

The Remove-PnPWeb cmdlet permanently removes a specific subsite. However, if your subsite has any child subsites, the script will end up with an error saying:
Remove-PnPWeb : There was a problem deleting Web site “/Sep”. Sites that have subsites or certain apps can’t be deleted. Please try again after deleting all subsites and removing the apps.

You’ll get a similar message when you try to delete a site with subsites using the web browser:

There was a problem deleting Web site. Sites that have subsites or certain apps can't be deleted. Please try again after deleting all subsites and removing the apps.

How to Delete a Site with all its subsites using PnP PowerShell?

As a SharePoint administrator, you may need to delete all the subsites in a site collection. We’ll show how to use PowerShell to delete all subsites in SharePoint Online. This is a handy trick if you need to clean up your site structure or if you’re starting from scratch and want to get rid of any existing subsites. Let’s delete all 1st level subsites under a given site (or subsite) in SharePoint Online:

#Subsite URL
$SiteURL = "https://crescent.sharepoint.com/sites/BoardPapers/September2020"

#Connect to subsite
Connect-PnPOnline -Url $SiteURL -Interactive

#Get all subsites and remove them
Get-PnPSubWebs | Remove-PnPWeb -Force

How about removing all subsites from all levels? Here is the PnP PowerShell to delete all Subsites recursively in SharePoint Online :

#Function to delete a subsite and its all child sites
Function Remove-PnPAllWebs([Microsoft.SharePoint.Client.Web]$Web) 
{
    #Get All Subsites of the web
    $SubWebs  = Get-PnPSubWeb -Identity $Web
    ForEach($SubWeb in $SubWebs)
    {
        #Call the function recursively to remove subsites
        Remove-PnPAllWebs($SubWeb)
    }
    #Delete the subsite
    Remove-PnPWeb -Identity $Web -Force
    Write-host -f Green "Deleted Sub-Site:"$Web.URL
}

#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/sales"

#Get Credentials to connect
$Cred = Get-Credential
 
#Connect PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials $Cred

#Get the Web 
$Web = Get-PnPWeb

#sharepoint online powershell delete all subsites
Remove-PnPAllWebs $Web

To delete a SharePoint Online site collection, you can use SharePoint Online Admin center in Microsoft 365 or PowerShell: How to Delete a SharePoint Online Site Collection?

How to disable subsite creation in SharePoint Online?

To disable subsite creation in SharePoint Online sites, do the following: Login to SharePoint Admin Center >> Click on Settings >> Classic settings >> under “Subsite creation” section, set “Hide the Subsite command” to Turn off SharePoint subsite creation on all sites and then click on the “Save” button at the bottom of the page to commit your changes.
More info: Disable subsite creation in SharePoint Online

How to create a modern subsite in SharePoint Online?

To add a subsite in SharePoint Online, follow these steps:
Sign in to your SharePoint Online site >> Click on Site Settings Gear Icon >> Choose “Site Contents”. On the toolbar, click on “New” and click on “Subsite” link (URL shortcut: /_layouts/15/newsbweb.aspx). Provide the Name, description, URL, and template for your new subsite. Specify other optional settings such as Permissions and Navigation. Click on the “Create” button at the bottom of the page to create a subsite in SharePoint Online.
More info: Add a subsite in SharePoint Online

How do I recover a deleted subsite in SharePoint Online?

To restore a subsite: Login to SharePoint Online Site collection as a site collection admin, Navigate to Site Settings >> Click on “Recycle bin” under site collection administration >> Click on “Second-stage recycle bin” >> Select the deleted subsite and Click on the “Restore” button to restoring the subsite. You can use PowerShell as well.
More info: SharePoint Online: Restore Deleted Subsite from Recycle Bin using PowerShell

How long can a deleted SharePoint site stay on the Recycle Bin?

93 days in SharePoint Online!

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

6 thoughts on “SharePoint Online: Delete a Subsite using PowerShell

  • Hi Salaudeen. Thanks for your site. There are so many fantastic scripts that have helped me a lot.
    I am trying the scripts above but I don’t have the ISAPI folder that you Load. Why would this be?
    I have installed SharePoint Online Management Shell.

    Reply
  • Hi Salaudeen,
    I tried delete the subsite but it deleted them permanently with no option to restore. could you please highlight or update with some text with Disclaimer that it does permanent delete

    Delete a subsite in SharePoint Online using PowerShell:

    Reply
    • True! Subsites deleted through PowerShell can’t be restored! This applies to any object deleted with .DeleteObject() method.

      Reply
  • Thanks for your help with this 🙂

    In the second script, add this line after try{
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))

    Otherwise it will get error for not authenticating.

    Thanks
    Mahmoud

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *