Enumerate Sharepoint 2010 database in PowerShell

“Is there a way to enumerate all SharePoint 2010 databases in PowerShell like the page /_admin/DatabaseStatus.aspx”>/_admin/DatabaseStatus.aspx”>http://<centra_administration>/_admin/DatabaseStatus.aspx does it??”

YES!

You can use this script:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") 

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local

$type = ('Microsoft.SharePoint.Administration.SPPersistedTypeCollection`1') -as "Type"
$type = $type.MakeGenericType( ("Microsoft.SharePoint.Administration.SPDatabase"as "Type") )
$o = [Activator]::CreateInstance($type, $farm)

$’

Now the variable “o” contains all Database-Objects of your farm!

How to create an instance of an generic class in PowerShell

Sometimes you may need to create instances of generic classes in PowerShell.

Like this (in C#):

 using  System;

 using  System.Text;
 
 namespace  tmp1
 {
     class  Program 
     {
         static  void  Main(string [] args)
         {
             System.Collections.Generic.List<string> t = new  System.Collections.Generic.List<string>();
         }
     }
 }

There is a generic class used in the code above: System.Collection.Generic.List.

If you want to create an instance of this class in PowerShell you can not use this:

New-Object "System.Collections.Generic.List<string>"

You’ll receive an error!

Here is the solution: You can use the System.Type that represents other .NET types.

Use this PowerShell code snipped to create an instance of System.Collections.Generic.List<string>

$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type = $type.MakeGenericType("system.string" -as "Type")
$o = [Activator]::CreateInstance($type)

“$o” will contain the created instance.

You can use this method for all other generic classes.

You may need to change the following details.

  1. In the first line of the snipped there is `+"1" This is the amount of parameters for the generic class.
  2. In the second line you have to specify the parameter types for the generic class. Separate them with “,” and cast them to System.Type by using -as “Type”.
  3. In the third line you may need to specify the constructor parameters for creating an instance of the generic class.

Here is another example:

$type = ("System.Collections.Generic.SortedList"+'`'+"2") -as "Type"
$type = $type.MakeGenericType( @( ("System.Int32" -as "Type"), ("system.string" -as "Type") ) )
$o = [Activator]::CreateInstance($type, 100)
$o.Add(1, "test")
$o

This creates an instance of System.Collections.Generic.SortedList<System.Int32, String> with a starting capacity of 10 (line 3: the second parameter of CreateInstance).