Koen Vosters

There is always a point in sharing.

This item cannot be deleted because it is still referenced by other pages.

The following error pops up when you are trying to remove a masterpage that is still being referenced. In SharePoint 2010 you can detect where the masterpages are being referenced through powershell. In the same script you can update the reference to make sure that there are no references left before you remove the masterpage.

In MOSS 2007 you had to put the masterpage in a subfolder before you were able to delete it. In SharePoint 2010 that should no longer be the case, but one of our partners reported an issue with it while trying to delete the masterpage. In the end it became clear that he forgot a few references (which will still not allow you to remove the masterpage even if it is in a subfolder), but just to be sure I give you the script including the subfolder move should you run into problems while trying to remove masterpages.

 Set-ExecutionPolicy Unrestricted 

#Load SharePoint Snapin

$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.PowerShell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin" -foregroundcolor Green
Add-PSSnapin "Microsoft.SharePoint.Powershell"
Write-Host "PowerShell Snapin Loaded" -foregroundcolor Green
}
else
{
Write-Host "SharePoint Powershell Snapin already loaded" -foregroundcolor Green
}

$site = Get-SPSite "http://www.contoso.com"
foreach ($web in $site.AllWebs)
{
if ($web.CustomMasterUrl -eq "/_catalogs/masterpage/MyCustom.master")
{
$web.CustomMasterUrl = "/_catalogs/masterpage/v4.master"
$web.Update()
}

}
#Get the rootweb that contains the masterpage gallery
$rootweb = Get-SPWeb -Identity http://www.contoso.com
if ($rootweb )
{
$masterpagesLibrary = $rootweb .GetFolder("_catalogs/masterpage")
$masterpage = $masterpagesLibrary.Files["MyCustom.master"]
if ($masterpage)
{
$spFolder = $masterpagesLibrary.DocumentLibrary.AddItem("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,"TempDeleteFolder")
$spFolder.Update()
$masterpage.MoveTo("/" + $masterpagesLibrary.Url + "/" + $spFolder.Name + "/" + $masterpage.Name)
$spFolder.Delete()
Write-Host "MasterPage Deleted" -foregroundcolor Green
}
else
{
Write-Host "Master Page not found" -foregroundcolor Red
}
$rootweb.Dispose()
}
else
{
Write-Host "Website not found" -foregroundcolor Red
}