我可以在不编写 SQL 查询的情况下找出数据库列表和 SQL Server 实例使用的空间吗?

2021-09-27 00:00:00 sql-server wmi

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

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.

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

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?

推荐答案

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

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

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

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"]);
        }
    }
}

相关文章