Reputation: 9644
I need to get a list of SQL server instances present on a computer, get a list of databases in each instance, and then determine how much space each database is taking up.
I can easily grab the instance names from the registry, but I don't have access to query the tables to get the names of the databases. Is there another way of doing this, maybe though WMI?
Upvotes: 0
Views: 4114
Reputation: 9644
After some digging around, I finally found the WMI Class that will get my the info I need. On a server where I have 3 instances of SQL Server, I found my data in the following classes
Win32_PerfFormattedData_MSSQLINST2_MSSQLINST2Databases
Win32_PerfFormattedData_MSSQLINST3_MSSQLINST3Databases
Win32_PerfFormattedData_MSSQLSERVER_SQLServerDatabases
My instances are MSSQLINST2
, MSSQLINST3
and MSSQLSERVER
. I couldn't figure out the naming scheme, so I had to look though all the classes to find out the information I needed. Anyway, here's the code that's working. Maybe someone will find it useful.
ManagementObjectSearcher sqlInstancesSearcher = new ManagementObjectSearcher(
new ManagementScope(@"Root\Microsoft\SqlServer\ComputerManagement10"),
new WqlObjectQuery("select * from SqlServiceAdvancedProperty where propertyindex = 12"),
null);
foreach (ManagementObject instance in sqlInstancesSearcher.Get())
{
string instanceName = instance["ServiceName"].ToString().Replace("$", String.Empty);
Console.WriteLine("INSTANCE: " + instanceName);
ManagementObjectSearcher classNameSearcher = new ManagementObjectSearcher(
new ManagementScope(@"root\cimv2"),
new WqlObjectQuery("select * from meta_class where __CLASS Like 'Win32_PerfFormattedData_" + instanceName + "%Databases%'"),
null);
foreach (ManagementClass wmiClass in classNameSearcher.Get())
{
string className = wmiClass["__CLASS"].ToString();
string query = "select * from " + className;
ManagementObjectSearcher databaseSearcher = new ManagementObjectSearcher(
new ManagementScope(@"root\cimv2"),
new WqlObjectQuery(query),
null);
foreach (ManagementObject database in databaseSearcher.Get())
{
Console.WriteLine(" " + database["Name"]);
Console.WriteLine(" Data Files : " + database["DataFilesSizeKB"]);
Console.WriteLine(" Log Files : " + database["LogFilesSizeKB"]);
Console.WriteLine(" Log Files Used : " + database["LogFilesSizeKB"]);
}
}
}
Upvotes: 2