List Unused Content Databases using PowerShell

Introduction

This script can be used to list your unused SharePoint content databases. It can also be used to list used content databases or all content databases.

Scenarios

By default, we can use Get-SPContentDatabase to retrieve SharePoint content databases. But this can only list the database that’s status is Ready. The content database cannot be listed if its status is Offline.

Script

This script contains one advanced function Get-OSCContentDatabase. You can use this in following ways:
Method 1:
1. Download the script and copy it to a Microsoft SharePoint 2010 server.
2. Open the script file by using Notepad or any other script editors.
3. Scroll down to the end of the script file, and then add the example command which you want to run.
4. Save the file, and then run the script in SharePoint 2010 Management Shell.
Method 2:
1. Rename scriptname.ps1 to scriptname.psm1 (PowerShell Module file)
2. Run Import-Module cmdlet to import this module file. Import-Module filepath\scriptname.psm1
Here are some code snippets for your references. To get the complete script sample, please click the download button at the beginning of this page.
PowerShell
Edit|Remove
[array]$arrContentDB = @() 
  try 
  { 
      Get-SPWebApplication -IncludeCentralAdministration | ForEach-Object{ 
          $arrContentDB +$_.ContentDatabases 
      } 
  } 
  catch [Exception] 
  { 
      #Catch and throw the terminating exception 
      throw $Error[0].Exception.Message 
  } 
  
$scriptContentDBOutput = @() 
  $scriptContentDBOutput += Export-OSCContentDatabase $arrContentDB 
  
#List the content databases which are in use currently 
  if($UsedDatabase) 
  { 
      Write-Host $Message.UsedDatabase 
      $scriptContentDBOutput = $scriptContentDBOutput | Where-Object{$_.Status -eq "Online"} 
      if($scriptContentDBOutput.Count -eq 0) 
      { 
          Write-Host $Message.ZeroUsedContentDB 
          return $null 
      } 
  }

Examples

Example 01: Display help about Get-OSCContentDatabase
Command: Get-Help Get-OSCContentDatabase
Screenshot:
  
Example 02: List all content databases
Command: Get-OSCContentDatabase
Screenshot:

 
Example 03: List the content databases which are in use currently.
Command: Get-OSCContentDatabase -UsedDatabase
Screenshot:

Example 04: List the content databases which are not in use currently.
Command: Get-OSCContentDatabase –UnUsedDatabase 
Screenshot:
  

Prerequisite

Windows PowerShell 2.0

Additional Resources

Related forum threads
http://social.technet.microsoft.com/Forums/en-US/sharepoint2010general/thread/e7ea930a-150e-4d4e-89e5-6fdd4e6379f7