WMI获取系统硬件软件信息

WMI是英文Windows   Management   Instrumentation的简写,它的功能主要是:访问本地主机的一些信息和服务,可以管理远程计算机(当然你必须要拥有足够的权限),比如:重启,关机,关闭进程,创建进程等。

 

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

namespace WMIManageState
{
    class Program
    {
        static void Main(string[] args)
        {
            string machineName = "10.10.50.44";
            string userName = string.Empty;
            string passWord = string.Empty;
            string doMain = string.Empty;

            // Build an options object for the remote connection
            //   if you plan to connect to the remote
            //   computer with a different user name
            //   and password than the one you are currently using

            ConnectionOptions options = new ConnectionOptions();
            options.Username = userName;
            options.Password = passWord;
            options.Authority = "ntlmdomain:" + doMain;

            // and then set the options.Username and
            // options.Password properties to the correct values
            // and also set
            // options.Authority = "ntdlmdomain:DOMAIN";
            // and replace DOMAIN with the remote computer's
            // domain.  You can also use kerberose instead
            // of ntdlmdomain.


            // Make a connection to a remote computer.
            // Replace the "FullComputerName" section of the
            // string "////FullComputerName//root//cimv2" with
            // the full computer name or IP address of the
            // remote computer.
            ManagementScope scope;

            if (userName.Length == 0 || passWord.Length == 0 || doMain.Length == 0)
                scope = new ManagementScope("////" + machineName + "//root//cimv2");
            else
                scope = new ManagementScope("////" + machineName + "//root//cimv2", options);
            try
            {
                scope.Connect();
            }
            catch (Exception connectionEx)
            {
                throw connectionEx;
            }

            PrintVideoModelInfo(scope);
            Console.WriteLine("----------------------------------------------------------------");
            PrintMemoryNumberInfo(scope);
            Console.WriteLine("----------------------------------------------------------------");
            //PrintGroupInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");

            //PrintComputerSystemInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");
            //PrintNetWorkConfigurationMACInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");
            //PrintNetWorkMACInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");
            //PrintLogicalDiskInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");
            //PrintDiskDriveInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");
            //PrintMotherBoardInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");
            //PrintOperatingSystemInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");
            //PrintShareInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");
            //PrintCpuInfo(scope);
            //Console.WriteLine("----------------------------------------------------------------");
            Console.ReadLine();
        }

        /// <summary>
        /// Win32_DiskDrive。返回硬盘驱动器信息,这个信息是磁盘的物理信息,比如簇大小、总大小、块大小、PNPID之类
        /// </summary>
        private static void PrintDiskDriveInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_DiskDrive");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection queryCollection = searcher.Get();

            foreach (ManagementBaseObject disk in queryCollection)
            {
                //foreach (PropertyData pd in disk.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}

                Console.WriteLine("硬盘ID:" + (string)disk.Properties["Model"].Value);
                Console.WriteLine("HardDisk Size:" + GetSizeUseUnit(disk.Properties["Size"].Value.ToString()));
            }
        }
        /// <summary>
        /// 打印逻辑驱动器信息,比如:C:,D:,E:
        /// </summary>
        private static void PrintLogicalDiskInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_LogicalDisk");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection queryCollection = searcher.Get();

            foreach (ManagementBaseObject disk in queryCollection)
            {
                //foreach (PropertyData pd in disk.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}
                Console.WriteLine(disk["Name"]);
                Console.WriteLine("Drive Type:" + GetDriveTypeName(disk["DriveType"].ToString()));
                if(disk["size"]!=null)
                Console.WriteLine("Total Space:"+GetSizeUseUnit(disk["size"].ToString()));
                if(disk["size"]!=null)
                Console.WriteLine("Free Space:" + GetSizeUseUnit(disk["freespace"].ToString()));
                Console.WriteLine("----------------------------------------------------------------");
                //Console.WriteLine("/r/n " + disk["Name"] + " " + disk["DriveType"] + " " + disk["VolumeName"]);
            }
        }
        /// <summary>
        /// 格式化驱动器大小
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        private static string GetSizeUseUnit(string size)
        {
            double dSpace = Convert.ToDouble(size);
            string sSpace = dSpace.ToString("N");
            string[] tmp;
            string rtnSize = "0";
            tmp = sSpace.Split(',');
            switch (tmp.GetUpperBound(0))
            {
                case 0:
                    rtnSize = tmp[0] + "bytes";
                    break;
                case 1:
                    rtnSize = tmp[0] + "." + tmp[1].Substring(0, 2) + " K";
                    break;
                case 2:
                    rtnSize = tmp[0] + "." + tmp[1].Substring(0, 2) + " M";
                    break;
                case 3:
                    rtnSize = tmp[0] + "." + tmp[1].Substring(0, 2) + " G";
                    break;
                case 4:
                    rtnSize = tmp[0] + "." + tmp[1].Substring(0, 2) + " T";
                    break;
            }
            return rtnSize;
        }
        /// <summary>
        /// 获取驱动器类型名称
        /// </summary>
        /// <param name="disk"></param>
        /// <returns></returns>
        private static string GetDriveTypeName(string driveType)
        {
            //驱动器类型
            string driveTypeName = string.Empty;
            try
            {
                switch (driveType)
                {
                    case "0":
                        driveTypeName="No Type";
                        break;
                    case "1":
                        driveTypeName="No Type";
                        break;
                    case "2":
                        driveTypeName="Floppy disk";
                        break;
                    case "3":
                        driveTypeName="Hard disk";
                        break;
                    case "4":
                        driveTypeName="Removable drive or network drive";
                        break;
                    case "5":
                        driveTypeName="CD_ROM";
                        break;
                    case "6":
                        driveTypeName="RAM Disk";
                        break;
                }
            }
            catch
            {
                driveTypeName="No Type";
            }
            return driveTypeName;
        }
        /// <summary>
        /// 打印主板信息
        /// </summary>
        private static void PrintMotherBoardInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From WIN32_BaseBoard");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection moc = searcher.Get();
            foreach (ManagementObject mo in moc)
            {
                //foreach (PropertyData pd in mo.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}

                Console.WriteLine("型号:" + mo["Product"].ToString());
                Console.WriteLine("序列号:" + mo["SerialNumber"].ToString());
                Console.WriteLine("主板制造商: " + mo["Manufacturer"].ToString());
            }
        }
        //获取主板序号
        private static string GetMotherBoardSerialNumber()
        {
            ManagementClass mc = new ManagementClass("WIN32_BaseBoard");
            ManagementObjectCollection moc = mc.GetInstances();
            string SerialNumber = "";
            foreach (ManagementObject mo in moc)
            {
                SerialNumber = mo["SerialNumber"].ToString();
                break;
            }
            return SerialNumber;
        }
        /// <summary>
        /// 打印操作系统信息
        /// </summary>
        private static void PrintOperatingSystemInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope,query);
            ManagementObjectCollection queryCollection = searcher.Get();

            foreach (ManagementBaseObject os in queryCollection)
            {
                //foreach (PropertyData pd in os.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}
                //Console.WriteLine("----------------------------------------------------------------");
                Console.WriteLine("Name:" + os["Name"].ToString());
                Console.WriteLine("Serial Number:" + os["SerialNumber"].ToString());
            }
        }
        private static void PrintShareInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_share");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope,query);
            ManagementObjectCollection queryCollection = searcher.Get();
            foreach (ManagementObject share in queryCollection)
            {
                Console.WriteLine(share.GetText(TextFormat.Mof));
            }
        }
        /// <summary>
        /// 收集CPU信息
        /// </summary>
        /// <param name="scope"></param>
        private static void PrintCpuInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_Processor");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection moc = searcher.Get();
            foreach (ManagementObject mo in moc)
            {
                //foreach (PropertyData pd in mo.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}

                Console.WriteLine("Name:" + mo["Name"].ToString());
                Console.WriteLine("Process ID:" + mo["ProcessorID"].ToString());
            }
        }
        /// <summary>
        /// 收集网卡信息
        /// </summary>
        /// <param name="scope"></param>
        private static void PrintNetWorkMACInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection moc = searcher.Get();
            foreach (ManagementObject mo in moc)
            {
                //foreach (PropertyData pd in mo.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}

                Console.WriteLine("ProductName:" + mo["ProductName"].ToString());
                Console.WriteLine("NetWorkCard:" + mo["Description"].ToString());
                if(mo["MAcaddress"]!=null)
                Console.WriteLine("Mac Address:" + mo["MAcaddress"].ToString());
                Console.WriteLine("----------------------------------------------------------------");
            }
        }
        /// <summary>
        /// 获取网卡硬件地址
        /// </summary>
        /// <param name="scope"></param>
        private static void PrintNetWorkConfigurationMACInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_NetworkAdapterConfiguration");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection moc = searcher.Get();
            foreach (ManagementObject mo in moc)
            {
                //foreach (PropertyData pd in mo.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}

                if ((bool)mo["IPEnabled"])
                    Console.WriteLine("Mac Address:" + mo["MAcaddress"].ToString());
                Console.WriteLine("----------------------------------------------------------------");
            }
        }
        /// <summary>
        /// 收集本地计算机信息
        /// </summary>
        /// <param name="scope"></param>
        private static void PrintComputerSystemInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_ComputerSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection moc = searcher.Get();
            foreach (ManagementObject mo in moc)
            {
                foreach (PropertyData pd in mo.Properties)
                {
                    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                }

                Console.WriteLine("Computer Name:" + mo["Name"].ToString());
                Console.WriteLine("Do Main:" + mo["DoMain"].ToString());
                Console.WriteLine("Physical Memery:" + System.Math.Round(Convert.ToDouble(mo["TotalPhysicalMemory"])/1024/1024) + " MB");
                Console.WriteLine("----------------------------------------------------------------");
            }
        }

        /// <summary>
        /// 获取用户组信息
        /// </summary>
        /// <returns></returns>
        private static void PrintGroupInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_Group");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection moCollection = searcher.Get();
            foreach (ManagementObject moGroup in moCollection)
            {
                //foreach (PropertyData pd in moGroup.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}
                Console.WriteLine("用户组="+moGroup["Name"].ToString());
                Console.WriteLine("----------------------------------------------------------------");
            }
        }

        /// <summary>
        /// 获取内存外频与数量信息
        /// </summary>
        /// <returns></returns>
        private static void PrintMemoryNumberInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_PhysicalMemory");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection moCollection = searcher.Get();
            foreach (ManagementObject moGroup in moCollection)
            {
                //foreach (PropertyData pd in moGroup.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}
                Console.WriteLine("Memory Tag:" + moGroup["Tag"].ToString());
                Console.WriteLine("Memery Capacity:" + System.Math.Round(Convert.ToDouble(moGroup["Capacity"]) / 1024 / 1024) + " MB");
                Console.WriteLine("----------------------------------------------------------------");
            }
        }

        /// <summary>
        /// 获取显卡信息
        /// </summary>
        /// <returns></returns>
        private static void PrintVideoModelInfo(ManagementScope scope)
        {
            SelectQuery query = new SelectQuery("Select * From Win32_VideoController");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection moCollection = searcher.Get();
            foreach (ManagementObject moGroup in moCollection)
            {
                //foreach (PropertyData pd in moGroup.Properties)
                //{
                //    Console.WriteLine(string.Format("{0}{1}{2}", pd.Name, "/t", pd.Value));
                //}
                Console.WriteLine("Video Controller:" + moGroup["Caption"].ToString());
                if(moGroup["VideoModeDescription"]!=null)
                Console.WriteLine("Video Mode Description:" + moGroup["VideoModeDescription"].ToString());
                Console.WriteLine("----------------------------------------------------------------");
            }
        }
    }
}

你可能感兴趣的:(WMI获取系统硬件软件信息)