0

我需要获取计算机上存在的 SQL Server 实例列表,获取每个实例中的数据库列表,然后确定每个数据库占用了多少空间。

我可以轻松地从注册表中获取实例名称,但我无权查询表以获取数据库的名称。是否有另一种方法可以做到这一点,也许是 WMI?

4

1 回答 1

2

经过一番挖掘,我终于找到了可以得到我需要的信息的 WMI 类。在我有 3 个 SQL Server 实例的服务器上,我在以下类中找到了我的数据

Win32_PerfFormattedData_MSSQLINST2_MSSQLINST2Databases
Win32_PerfFormattedData_MSSQLINST3_MSSQLINST3Databases
Win32_PerfFormattedData_MSSQLSERVER_SQLServerDatabases

我的实例MSSQLINST2MSSQLINST3MSSQLSERVER。我无法弄清楚命名方案,所以我不得不查看所有类以找出我需要的信息。无论如何,这是有效的代码。也许有人会发现它很有用。

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"]);
        }
    }
}
于 2012-04-26T20:46:28.120 回答