PowerShell script to get orphan objects in the SharePoint farm.
$LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
$LogFile = ".\FindOrphanSitesPatch-$LogTime.rtf"
# Add SharePoint PowerShell Snapin
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {
Add-PSSnapin Microsoft.SharePoint.Powershell
}
$scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
Set-Location $scriptBase
#Deleting any .rtf files in the scriptbase location
$FindRTFFile = Get-ChildItem $scriptBase\*.* -include *.rtf
if($FindRTFFile)
{
foreach($file in $FindRTFFile)
{
remove-item $file
}
}
start-transcript $logfile
Function GetAllWebApplicationsInFarm()
{
$spFarm = [Microsoft.SharePoint.Administration.SPfarm]::Local
Write-host Reporting orphaned sites on the farm $spFarm.Name
$spUrls = $spFarm.AlternateUrlCollections
$spWebApplicationUrls = $spUrls | foreach {$_ | foreach {$_.incomingurl}}
Return $spWebApplicationUrls
}
$AllWebApplications = GetAllWebApplicationsInFarm
If ($AllWebApplications)
{
ForEach ($WebApplicationUri in $AllWebApplications)
{
Write-host "Retrieving the content databases of the web application $WebApplicationUri"
[XML]$ContentDBs = stsadm -o enumcontentdbs -url $WebApplicationUri
If ($ContentDBs)
{
ForEach ($ContentDB in $ContentDBs.Databases.ContentDatabase)
{
$ContentDBName = $ContentDB.Name
Write-host "Analyzing content database $ContentDBName"
[XML]$OrphanedSites = stsadm -o databaserepair -url $WebApplicationUri -databasename $ContentDBName
[INT]$OrphanedSitesCount = $OrphanedSites.OrphanedObjects.Count
If ($OrphanedSitesCount -gt 0)
{Write-Host "Content database $ContentDBName contains $OrphanedSitesCount orphaned sites" -fore green}
Else {Write-host "Content database $ContentDBName does not contain any orphaned site" -fore cyan}
}
}
Else {Write-Error "Unable to retrieve the list of content databases for application $WebApplicationUri"}
}
}
Else {Write-Error "Unable to retrieve the list of web applications"}
stop-transcriptThis code describes the Powershell script to get orphan objects in the sharepoint farm
