Thursday, August 4, 2011

Programmatically Enumerating Databases in SharePoint 2010

See below -

using (SPSite site = new SPSite(url))

{

    using (SPWeb web = site.OpenWeb())

    {

        SPFarm f = site.WebApplication.Farm;

        foreach (SPDatabaseService s in f.Services.OfType<SPDatabaseService>())

        {

            Console.WriteLine(string.Format("Found Database service {0} of type {1}",

                s.Name, s.GetType().Name));

            foreach (SPDatabaseServiceInstance spdsi in s.Instances)

            {

                Console.WriteLine(string.Format("|-Found Database Service Instance {0} ({1})",

                    spdsi.DisplayName, spdsi.Name));

                foreach (SPDatabase spdb in spdsi.Databases)

                {

                    Console.WriteLine(

                        string.Format("  |-DB: {0}\r\n    |-TYPE: {1}\r\n    |-HOST: {2} ",

                        spdb.Name.Length > 70 ? spdb.Name.Substring(0, 65) + "..." : spdb.Name,

                        spdb.GetType().Name, spdb.Server.Name)

                        );

                }

            }

        }

    }

}

Results look something like:

image

No comments:

Post a Comment