Technology Toolbox

Your technology Sherpa for the Microsoft platform

Jeremy Jameson - Founder and Principal

Search

Search

Using PowerShell to Delete a Site with Subsites in SharePoint Server 2010

Note
This post originally appeared on my MSDN blog:

Since I no longer work for Microsoft, I have copied it here in case that blog ever goes away.

When using the "DR.DADA" approach to SharePoint development, I often find myself deleting sites (in DEV and TEST environments) and subsequently re-activating features or running some migration utility to recreate the site hierarchy.

In fact, a few years ago this became such a common task on the Agilent Technologies project that I wrote a simple "DeleteWeb" program to overcome the fact that stsadm.exe -o deleteweb doesn't work on sites that have subsites.

Note that there really wasn't much to the DeleteWeb program. Almost all of the work was performed by the DeleteHelper class:

using System;
using System.Diagnostics;
using System.Globalization;

using Microsoft.SharePoint;

namespace DeleteWeb
{
    public sealed class DeleteHelper
    {
        private DeleteHelper() { } // all members are static

        public static void DeleteWeb(
            string siteUrl)
        {
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    if (string.Compare(web.Url, siteUrl, true,
                        CultureInfo.InvariantCulture) != 0)
                    {
                        throw new InvalidOperationException(
                            "Invalid Web URL. Verify the URL and try again.");
                    }

                    DeleteWeb(web);
                }
            }
        }

        public static void DeleteWeb(
            SPWeb web)
        {
            SPWebCollection subwebs = web.GetSubwebsForCurrentUser();

            if (subwebs.Count > 0)
            {
                foreach (SPWeb subweb in subwebs)
                {
                    DeleteWeb(subweb);
                    subweb.Dispose();
                }
            }

            Debug.WriteLine("Deleting web: " + web.ServerRelativeUrl);
            web.Delete();
            return;
        }
    }
}

I was hoping that SharePoint Server 2010 would address this scenario out-of-the-box, but that doesn't appear to be the case.

Suppose that you have a site (e.g. http://foobar/Test) that has subsites (e.g. http://foobar/Test/foo and http://foobar/Test/bar). If you attempt to use the Remove-SPWeb cmdlet in SharePoint Server 2010 to delete the site...

Remove-SPWeb "http://foobar/Test" -Confirm:$false

...then you will encounter an error similar to the following:

Remove-SPWeb : Error deleting Web site "/Test". You can't delete a site that has subsites.
At line:1 char:13
+ Remove-SPWeb <<<< "http://foobar/Test" -Confirm:$false
+ CategoryInfo : InvalidData: (Microsoft.Share...CmdletRemoveWeb:SPCmdletRemoveWeb) [Remove-SPWeb], SPException
+ FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletRemoveWeb

In order to delete a site that has subsites using PowerShell, we simply need to convert the C# code shown above into a corresponding PowerShell function, as shown below:

# Completely deletes the specified Web (including all subsites)

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://foobar/Test"
$DebugPreference = "Continue"

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

Note that the script handles the case where $web is null -- in other words, when the specified Web doesn't exist (for example, when running the script a second time).

Comments

  1. # re: Using PowerShell to Delete a Site with Subsites in SharePoint Server 2010

    May 10, 2011 6:16 PM
    ok

    you're awesome.  That was a great script to delete the webs.  

    Greg

  2. # re: Using PowerShell to Delete a Site with Subsites in SharePoint Server 2010

    May 24, 2011 11:59 AM
    Need ur favour

    Hi Jameson,

    This is a nice script,However I have a small requirement like,I need the List of MySites which are currently existing and What all users have those MySites and they belong to which OU in AD.

    Could you please post any links you have?

  3. # re: Using PowerShell to Delete a Site with Subsites in SharePoint Server 2010

    May 15, 2012 9:13 PM
    Sanjai
    Hi Jameson

    Thank you ..Script is very good, got my work done...

    once again thank you for sharing.

    Regards,
    Sanjai
  4. # re: Using PowerShell to Delete a Site with Subsites in SharePoint Server 2010

    April 30, 2013 5:15 AM
    David Piscopo
    Gravatar
    Doesn't work for me (SharePoint 2010). $subwebs = $web.GetSubwebsForCurrentUser() throws an exception:

    Exception calling "GetSubwebsForCurrentUser" with "0" argument(s): "Unable to cast COM object of type 'Microsoft.SharePoint.Library.SPRequestInternalClass' to interf
    ace type 'Microsoft.SharePoint.Library.ISPRequest'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{BDEADF28-
    C265-11D0-BCED-00A0C90AB50F}' failed due to the following error: Bad variable type. (Exception from HRESULT: 0x80020008 (DISP_E_BADVARTYPE))."
    At C:\Users\Administrator\AppData\Local\Temp\4be56fee-af7d-4818-921d-b26c3828c589.ps1:23 char:45
    + $subwebs = $web.GetSubwebsForCurrentUser <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
  5. # re: Using PowerShell to Delete a Site with Subsites in SharePoint Server 2010

    April 30, 2013 2:48 PM
    Jeremy Jameson
    Gravatar
    David,

    Sorry, but I don't really know what to say. This works for me and, from the comments can see above, it works for others as well.

    My only guess is that you have installed a SharePoint Cumulative Update from Microsoft in your environment and this broke the ability to use this script.

    I'm only speculating here -- since I can't say for sure without troubleshooting your specific environment. However, I will say that the SharePoint Product Group has become somewhat notorious over the years for introducing bugs in their patches. (The SharePoint 2010 SP1 debacle with the User Profile Service comes immediately to mind.)
  6. # re: Using PowerShell to Delete a Site with Subsites in SharePoint Server 2010

    September 23, 2013 6:34 PM
    Shola Salako
    Gravatar
    Great PowerShell script! Thanks for sharing this...it saved my team a lot of time on a critical project. Cheers!

Add Comment

Optional, but recommended (especially if you have a Gravatar). Note that your email address will not appear with your comment.
If URL is specified, it will be included as a link with your name.

To prevent spam from being submitted, please select the following fruit: Grapes

Watermelon
Apple
Pear
Cherries
Grapes
Strawberry
 
Please add 7 and 8 and type the answer here: