Friday, January 31, 2014

PowerShell to delete site collection completely

If we delete a site collection through PowerShell command "Remove-SPSite" without "-GradualDelete" parameter, the site collection is removed from content database completely.

However, if we delete the site collection through CA, CA deletes it with "-GradualDelete". So if we want to recreate the site collection with the same URL, it will fail.

Below is the script to force removing the SPSite from the content database.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue"

cls

function CompleteSPSiteRemove([string]$SiteUrl)
{
    $oSite = Get-SPSite $SiteUrl -ErrorAction SilentlyContinue
    if($null -ne $oSite)
    {
        $WebApp = $oSite.WebApplication
        $SiteID = $oSite.ID

        Remove-SPSite $SiteUrl -confirm:$false
    }
    else
    {
        $WebApp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($SiteUrl)
        Get-SPDeletedSite -WebApplication $WebApp | Remove-SPDeletedSite -confirm:$false
    }

    $job = Get-SPTimerJob | ?{$_.Title -match "Gradual Site Delete"} | ?{$_.Parent -eq $WebApp}
    if($null -ne $job)
    {
        Write-Host -ForegroundColor Yellow "Starting "$job.DisplayName
        $job | Format-List *
        $job | Start-SPTimerJob
    }
}

CompleteSPSiteRemove "http://MySiteDev.company.local/sites/site1"

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host


References:

http://reality-tech.com/2012/04/04/gradual-site-collection-deletion/



No comments:

Post a Comment