簡體   English   中英

如何通過WMI查詢獲取GB中的總物理內存(RAM)信息?

[英]How to get total physical memory (ram) information in GB by WMI query?

我知道如何從win32_computersystem類獲取總物理內存。 但以字節或kb表示。 我想要此信息以MB或GB為單位。 在WMI(WQL)查詢中。 WMIC也可以。 提前致謝。

您必須手動轉換屬性的值。 也最好使用Win32_PhysicalMemory WMI類。

試試這個樣本

using System;
using System.Collections.Generic;
using System.Management;
using System.Text;

namespace GetWMI_Info
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                ManagementScope Scope;
                Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", "."), null);

                Scope.Connect();
                ObjectQuery Query = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory");
                ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
                UInt64 Capacity = 0;
                foreach (ManagementObject WmiObject in Searcher.Get())
                {
                    Capacity+= (UInt64) WmiObject["Capacity"];
                }
                Console.WriteLine(String.Format("Physical Memory {0} gb", Capacity / (1024 * 1024 * 1024))); 
                Console.WriteLine(String.Format("Physical Memory {0} mb", Capacity / (1024 * 1024)));
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
            }
            Console.WriteLine("Press Enter to exit");
            Console.Read();
        }
    }
}

您可以轉換Win32_ComputerSystem的 TotalPhysicalMemory 嘗試這個 :

using System;
using System.Management;
namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("root\\CIMV2",
                    "SELECT TotalPhysicalMemory FROM Win32_ComputerSystem");

                foreach (ManagementObject queryObj in searcher.Get())
                { 
                    double dblMemory;
                    if(double.TryParse(Convert.ToString(queryObj["TotalPhysicalMemory"]),out dblMemory))
                    {
                        Console.WriteLine("TotalPhysicalMemory is: {0} MB", Convert.ToInt32(dblMemory/(1024*1024)));
                        Console.WriteLine("TotalPhysicalMemory is: {0} GB", Convert.ToInt32(dblMemory /(1024*1024*1024)));
                    }
                }
            }
            catch (ManagementException e)
            {

            }
        }
    }
}

想要提及的是,在Windows Server 2012上遇到不一致的結果之前,我一直使用Win32_PhysicalMemory Capacity屬性。現在我同時使用兩個屬性(Win32_ComputerSystem:TotalPhysicalMemory和Win32_PhysicalMemory:Capacity),然后選擇兩者中較大的一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM