PowerShell Script to get Orphan Objects in the SharePoint Farm

  1. PowerShell script to get orphan objects in the SharePoint farm.  
  2.    
  3. $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm  
  4. $LogFile = ".\FindOrphanSitesPatch-$LogTime.rtf"  
  5.  
  6. # Add SharePoint PowerShell Snapin  
  7.   
  8.   
  9. if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {  
  10.     Add-PSSnapin Microsoft.SharePoint.Powershell  
  11. }  
  12.   
  13. $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent  
  14. Set-Location $scriptBase  
  15.  
  16.  
  17. #Deleting any .rtf files in the scriptbase location  
  18. $FindRTFFile = Get-ChildItem $scriptBase\*.* -include *.rtf  
  19. if($FindRTFFile)  
  20. {  
  21.  foreach($file in $FindRTFFile)  
  22.   {  
  23.    remove-item $file  
  24.   }  
  25. }  
  26.   
  27.   
  28. start-transcript $logfile  
  29.   
  30. Function GetAllWebApplicationsInFarm()  
  31. {  
  32.  $spFarm = [Microsoft.SharePoint.Administration.SPfarm]::Local  
  33.  Write-host Reporting orphaned sites on the farm $spFarm.Name  
  34.  $spUrls = $spFarm.AlternateUrlCollections  
  35.  $spWebApplicationUrls = $spUrls | foreach {$_ | foreach {$_.incomingurl}}  
  36.  Return $spWebApplicationUrls  
  37. }  
  38.   
  39. $AllWebApplications = GetAllWebApplicationsInFarm  
  40. If ($AllWebApplications)  
  41. {  
  42.  ForEach ($WebApplicationUri in $AllWebApplications)  
  43.  {  
  44.   Write-host "Retrieving the content databases of the web application $WebApplicationUri"  
  45.     
  46.   [XML]$ContentDBs = stsadm -o enumcontentdbs -url $WebApplicationUri  
  47.   If ($ContentDBs)  
  48.   {  
  49.    ForEach ($ContentDB in $ContentDBs.Databases.ContentDatabase)  
  50.    {  
  51.     $ContentDBName = $ContentDB.Name  
  52.     Write-host "Analyzing content database $ContentDBName"  
  53.     [XML]$OrphanedSites = stsadm -o databaserepair -url $WebApplicationUri -databasename $ContentDBName  
  54.     [INT]$OrphanedSitesCount = $OrphanedSites.OrphanedObjects.Count  
  55.     If ($OrphanedSitesCount -gt 0)  
  56.     {Write-Host "Content database $ContentDBName contains $OrphanedSitesCount orphaned sites" -fore green}  
  57.     Else {Write-host "Content database $ContentDBName does not contain any orphaned site" -fore cyan}  
  58.    }  
  59.   }  
  60.   Else {Write-Error "Unable to retrieve the list of content databases for application $WebApplicationUri"}  
  61.  }  
  62. }  
  63. Else {Write-Error "Unable to retrieve the list of web applications"}  
  64.   
  65. stop-transcript