問題描述
我需要獲取計算機上存在的 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
我的實例是 MSSQLINST2
、MSSQLINST3
和 MSSQLSERVER
.我無法弄清楚命名方案,所以我不得不查看所有類以找出我需要的信息.無論如何,這是有效的代碼.也許有人會發現它很有用.
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"]);
}
}
}
這篇關于我可以在不編寫 SQL 查詢的情況下找出數據庫列表和 SQL Server 實例使用的空間嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!