Powwershell Script to Find Unused (Offline) Content Databases in SharePoint 2010

  1. $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm  
  2. $LogFile = ".\UnusedContentDatabasesPatch-$LogTime.rtf"  
  3.  
  4. # Add SharePoint PowerShell Snapin  
  5.   
  6.   
  7. if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {  
  8.     Add-PSSnapin Microsoft.SharePoint.Powershell  
  9. }  
  10.   
  11. $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent  
  12. Set-Location $scriptBase  
  13.  
  14.  
  15. #Deleting any .rtf files in the scriptbase location  
  16. $FindRTFFile = Get-ChildItem $scriptBase\*.* -include *.rtf  
  17. if($FindRTFFile)  
  18. {  
  19.  foreach($file in $FindRTFFile)  
  20.   {  
  21.    remove-item $file  
  22.   }  
  23. }  
  24.   
  25.   
  26. start-transcript $logfile  
  27.   
  28. Function UnUsedContentDatabases()  
  29. {  
  30.   
  31.  $Output = $scriptBase + "\" + "UnUsedCDBs.csv";  
  32.  "UnUsedCDBs" | Out-File -Encoding Default -FilePath $Output;  
  33.  Write-host "Collecting information on used content databases" -fore yellow  
  34.  $webapplications = get-spwebapplication -IncludeCentralAdministration  
  35.  foreach($webapplication in $webapplications)  
  36.  {  
  37.   $CDBs = $webapplication.contentdatabases  
  38.   write-host "Total count of content databases associated with the webapp " $webapplication.url " is " $webapplication.contentdatabases.count -fore magenta  
  39.   foreach($CDB in $CDBs)  
  40.   {  
  41.    if($CDB.status -ne "Online")  
  42.    {  
  43.     write-host "The content database " $CDB.name " is offline and it is not in use" -for green  
  44.     $CDB.name | Out-File -Encoding Default  -Append -FilePath $Output;  
  45.    }  
  46.      
  47.   }  
  48.  }  
  49.  write-host "Output file generated and located at " $output -fore yellow  
  50.   
  51. }  
  52.   
  53. UnUsedContentDatabases  
  54.   
  55. stop-transcript