private void CountQueueMessages(QSetQueueItem queueItem) { //first of all, ensure we have a node to work with QueueItemListViewItemPair itemPair = null; if (_itemPairHashTable.ContainsKey(queueItem.ID)) { itemPair = (QSetMonitorWorker.QueueItemListViewItemPair)_itemPairHashTable[queueItem.ID]; } else { //TODO create icon itemPair = new QueueItemListViewItemPair(queueItem, new ListViewItem(queueItem.Name, (int)Images.IconType.Queue)); for (int subItemCounter = 0; subItemCounter < _COLUMNS; subItemCounter++) { itemPair.ListViewItem.SubItems.Add(string.Empty); } _itemPairHashTable.Add(itemPair.QSetQueueItem.ID, itemPair); Action x = delegate { _monitorListView.Items.Add(itemPair.ListViewItem); }; _monitorListView.Invoke(x); } ManagementObject counter = null; try { counter = new ManagementObject(String.Format("Win32_PerfRawdata_MSMQ_MSMQQueue.name='{0}'", itemPair.QSetQueueItem.Name)); counter.Get(); uint outgoingMessageCount = Convert.ToUInt32(counter.GetPropertyValue("MessagesInQueue")); uint outgoingBytes = Convert.ToUInt32(counter.GetPropertyValue("BytesInQueue")); Action herewegoagain = () => { if (itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingMessageCount].Text != outgoingMessageCount.ToString()) //note: only do if necessary, to avoid flicker { itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingMessageCount].Text = outgoingMessageCount.ToString(); } if (itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingBytes].Text != outgoingBytes.ToString()) //note: only do if necessary, to avoid flicker { itemPair.ListViewItem.SubItems[(int)SubItemList.OutgoingBytes].Text = outgoingBytes.ToString(); } }; _monitorListView.Invoke(herewegoagain); } catch { //exception will occur when cannot get access to performance counters } finally { if (counter != null) { counter.Dispose(); } } }
private static VirtualMachineNetworkInfo[] GetNetworksByAdapters(Guid vmId, MinimizedVMNetworkAdapter[] networkAdapters) { var scope = new ManagementScope(@"\\.\root\virtualization\v2"); var resultList = new List <VirtualMachineNetworkInfo>(); foreach (var networkAdapter in networkAdapters) { var guestNetworkId = networkAdapter.Id.Replace("Microsoft:", "Microsoft:GuestNetwork\\").Replace("\\", "\\\\"); var obj = new ManagementObject(); var path = new ManagementPath(scope.Path + $":Msvm_GuestNetworkAdapterConfiguration.InstanceID=\"{guestNetworkId}\""); obj.Path = path; obj.Get(); var info = new VirtualMachineNetworkInfo { AdapterName = networkAdapter.Name, IPAddresses = ObjectToStringArray(obj.GetPropertyValue("IPAddresses")), DefaultGateways = ObjectToStringArray(obj.GetPropertyValue("DefaultGateways")), DnsServers = ObjectToStringArray(obj.GetPropertyValue("DNSServers")), DhcpEnabled = (bool)obj.GetPropertyValue("DHCPEnabled") }; info.Subnets = AddressesAndSubnetsToSubnets(info.IPAddresses, ObjectToStringArray(obj.GetPropertyValue("Subnets"))).ToArray(); resultList.Add(info); } return(resultList.ToArray()); }
static List <string> GetBootEntries(ManagementObject BcdStore, ManagementScope managementScope) { var bootEntries = new List <string>(); var inParams = BcdStore.GetMethodParameters("GetElement"); // 0x24000001 is a BCD constant: BcdBootMgrObjectList_DisplayOrder inParams["Type"] = ((UInt32)0x24000001); ManagementBaseObject outParams = BcdStore.InvokeMethod("GetElement", inParams, null); ManagementBaseObject mboOut = ((ManagementBaseObject)(outParams.Properties["Element"].Value)); string[] osIdList = (string[])mboOut.GetPropertyValue("Ids"); // Each osGuid is the GUID of one Boot Manager in the BcdStore foreach (string osGuid in osIdList) { ManagementObject currentManObj = new ManagementObject(managementScope, new ManagementPath("root\\WMI:BcdObject.Id=\"" + osGuid + "\",StoreFilePath=\"\""), null); var id = currentManObj.GetPropertyValue("Id"); bootEntries.Add((string)currentManObj.GetPropertyValue("Id")); } return(bootEntries); }
public static Dictionary <string, string> GetMountPointVolumeIDMappings(out Exception ex) { Dictionary <string, string> mountPointVolumeIdMappings = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase); ex = null; ManagementObjectCollection mountPointToVolumeMappings = WMIUtil.GetManagementObjectCollection("Win32_MountPoint", "\\ROOT\\CIMV2", out ex); if (mountPointToVolumeMappings == null) { return(null); } ex = Util.HandleExceptions(delegate { using (ManagementObjectCollection mountPointToVolumeMappings = mountPointToVolumeMappings) { foreach (ManagementBaseObject managementBaseObject in mountPointToVolumeMappings) { ManagementObject managementObject = (ManagementObject)managementBaseObject; using (managementObject) { string input = managementObject.GetPropertyValue("Volume").ToString(); string input2 = managementObject.GetPropertyValue("Directory").ToString(); string pattern = "\"(.*)\""; Match match = Regex.Match(input, pattern); Match match2 = Regex.Match(input2, pattern); if (match.Success && match2.Success) { mountPointVolumeIdMappings.Add(Util.RemoveEscapeCharacters(match2.Groups[1].Value), Util.RemoveEscapeCharacters(match.Groups[1].Value)); } } } } }); return(mountPointVolumeIdMappings); }
// Token: 0x060000FB RID: 251 RVA: 0x0000BC48 File Offset: 0x00009E48 private static string GetMotherBoard() { string result = string.Empty; foreach (ManagementBaseObject managementBaseObject in new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM CIM_Card").Get()) { ManagementObject managementObject = (ManagementObject)managementBaseObject; try { result = string.Concat(new string[] { "Manufacturer - ", managementObject.GetPropertyValue("Manufacturer").ToString(), ", product - ", managementObject.GetPropertyValue("Product").ToString(), ", serialnumber - ", managementObject.GetPropertyValue("SerialNumber").ToString(), ", version - ", managementObject.GetPropertyValue("Version").ToString() }); } catch { } } return(result); }
public void Update(ManagementObject mCfg, ManagementObject mAdap) { moConfig = mCfg; moAdapter = mAdap; Caption = (string)moConfig["Caption"]; Description = (string)moConfig["Description"]; DHCPEnabled = (bool)moConfig["DHCPEnabled"]; string[] ip = (string[])moConfig.GetPropertyValue("IPAddress"); string[] sub = (string[])moConfig.GetPropertyValue("IPSubnet"); string[] gw = (string[])moConfig.GetPropertyValue("DefaultIPGateway"); bool newEnabled = (bool)moConfig["IPEnabled"]; string newIPAddress = ip != null ? ip[0] : string.Empty; string newSubmask = sub != null ? sub[0] : string.Empty; string newGateway = gw != null ? gw[0] : string.Empty; if (newIPAddress.ToLowerInvariant().Trim() != IPAddress.ToLowerInvariant().Trim() || newSubmask.ToLowerInvariant().Trim() != Submask.ToLowerInvariant().Trim() || newGateway.ToLowerInvariant().Trim() != Gateway.ToLowerInvariant().Trim() || newEnabled != Enabled) { Changed?.Invoke(this, null); } IPAddress = newIPAddress; Submask = newSubmask; Gateway = newGateway; Enabled = newEnabled; }
public static Dictionary <string, string> GetPairedNxtBluetoothBTAddress() { SelectQuery WMIquery = new SelectQuery(QueryString); ManagementObjectSearcher WMIqueryResults = new ManagementObjectSearcher(WMIquery); Dictionary <string, string> comPorts = new Dictionary <string, string>(); if (WMIqueryResults != null) { foreach (object result in WMIqueryResults.Get()) { ManagementObject mo = (ManagementObject)result; object captionObject = mo.GetPropertyValue("Caption"); object pnpIdObject = mo.GetPropertyValue("PNPDeviceID"); // Get the COM port name out of the Caption, requires a little work. string caption = captionObject.ToString(); string comPort = caption.Substring(caption.LastIndexOf("(COM")). Replace("(", string.Empty).Replace(")", string.Empty); // Extract the BT address from the PNPObjectID property string BTaddress = pnpIdObject.ToString().Split('&')[4].Substring(0, 12); comPorts.Add(comPort, BTaddress); } } return(comPorts); }
/// <summary> /// Gets the outgoing COM Serial Port of a bluetooth device. /// </summary> /// <param name="deviceAddress"></param> /// <returns></returns> private static string GetBluetoothPort(string deviceAddress) { const string Win32_SerialPort = "Win32_SerialPort"; SelectQuery q = new SelectQuery(Win32_SerialPort); ManagementObjectSearcher s = new ManagementObjectSearcher(q); foreach (object cur in s.Get()) { ManagementObject mo = (ManagementObject)cur; string pnpId = mo.GetPropertyValue("PNPDeviceID").ToString(); if (pnpId.Contains(deviceAddress)) { object captionObject = mo.GetPropertyValue("Caption"); string caption = captionObject.ToString(); int index = caption.LastIndexOf("(COM"); if (index > 0) { string portString = caption.Substring(index); string comPort = portString. Replace("(", string.Empty).Replace(")", string.Empty); return(comPort); } } } return(null); }
// Updates the NicInfo struct // Uses WMI to extract information about network adapters public void UpdateNicInfo() { NicInfo n = new NicInfo(); NicList.Clear(); foreach (ManagementObject a in AdapterCollection) { if ((bool)a.GetPropertyValue("PhysicalAdapter")) { // Get info from AdapterColection n.DeviceID = (string)a.GetPropertyValue("DeviceID"); n.Name = (string)a.GetPropertyValue("NetConnectionID"); n.Description = (string)a.GetPropertyValue("Description"); n.NetEnabled = (bool)a.GetPropertyValue("NetEnabled"); // Fetch one specific adapter configuration based on DeviceID ManagementObject mo = new ManagementObject("Win32_NetworkAdapterConfiguration.Index=" + n.DeviceID); // Get IP info from that configuration n.DHCP = (bool)mo.GetPropertyValue("DHCPEnabled"); n.IpAddress = (string[])mo.GetPropertyValue("IPAddress"); n.SubnetMask = (string[])mo.GetPropertyValue("IPSubnet"); n.Gateway = (string[])mo.GetPropertyValue("DefaultIPGateway"); n.DNS = (string[])mo.GetPropertyValue("DNSServerSearchOrder"); NicList.Add(n); mo.Dispose(); } } }
private static Service Map(ManagementObject mo) { return(new Service { ServiceName = mo.GetPropertyValue("Name").ToString(), DisplayName = mo.GetPropertyValue("DisplayName").ToString(), DescriptionWithCommandLine = mo.GetPropertyValue("Description").ToString(), ProcessId = int.Parse(mo.GetPropertyValue("ProcessID").ToString()) }); }
DisplayResourcePool( ManagementObject pool) { Console.WriteLine("Msvm_ResourcePool:"); Console.WriteLine("\tPoolID: {0}", pool.GetPropertyValue("PoolID")); Console.WriteLine("\tInstanceID: {0}", pool.GetPropertyValue("InstanceID")); Console.WriteLine("\tResourceType: {0}", pool.GetPropertyValue("ResourceType")); Console.WriteLine("\tResourceSubtype: {0}", pool.GetPropertyValue("ResourceSubType")); }
public SerialPortInfo(ManagementObject property, ILogger logger) { /* These are not needed but are retained here in case they might be useful for diagnosing surprises. * this.Availability = property.GetPropertyValue("Availability") as int? ?? 0; * this.Caption = property.GetPropertyValue("Caption") as string ?? string.Empty; * this.ClassGuid = property.GetPropertyValue("ClassGuid") as string ?? string.Empty; * this.CompatibleID = property.GetPropertyValue("CompatibleID") as string[] ?? new string[] { }; * this.ConfigManagerErrorCode = property.GetPropertyValue("ConfigManagerErrorCode") as int? ?? 0; * this.ConfigManagerUserConfig = property.GetPropertyValue("ConfigManagerUserConfig") as bool? ?? false; * this.CreationClassName = property.GetPropertyValue("CreationClassName") as string ?? string.Empty; * this.Description = property.GetPropertyValue("Description") as string ?? string.Empty; * this.ErrorCleared = property.GetPropertyValue("ErrorCleared") as bool? ?? false; * this.ErrorDescription = property.GetPropertyValue("ErrorDescription") as string ?? string.Empty; * this.HardwareID = property.GetPropertyValue("HardwareID") as string[] ?? new string[] { }; * this.InstallDate = property.GetPropertyValue("InstallDate") as DateTime? ?? DateTime.MinValue; * this.LastErrorCode = property.GetPropertyValue("LastErrorCode") as int? ?? 0; * this.Manufacturer = property.GetPropertyValue("Manufacturer") as string ?? string.Empty; * this.PNPClass = property.GetPropertyValue("PNPClass") as string ?? string.Empty; * this.PNPDeviceID = property.GetPropertyValue("PNPDeviceID") as string ?? string.Empty; * this.PowerManagementCapabilities = property.GetPropertyValue("PowerManagementCapabilities") as int[] ?? new int[] { }; * this.PowerManagementSupported = property.GetPropertyValue("PowerManagementSupported") as bool? ?? false; * this.Present = property.GetPropertyValue("Present") as bool? ?? false; * this.Service = property.GetPropertyValue("Service") as string ?? string.Empty; * this.Status = property.GetPropertyValue("Status") as string ?? string.Empty; * this.StatusInfo = property.GetPropertyValue("StatusInfo") as int? ?? 0; * this.SystemCreationClassName = property.GetPropertyValue("SystemCreationClassName") as string ?? string.Empty; * this.SystemName = property.GetPropertyValue("SystemName") as string ?? string.Empty; */ this.Name = property.GetPropertyValue("Name") as string ?? string.Empty; this.DeviceID = property.GetPropertyValue("DeviceID") as string ?? string.Empty; this.PortName = GetPortName(this.DeviceID, logger); if (!string.IsNullOrEmpty(this.PortName) && !this.Name.Contains("(LPT") && this.PortName.StartsWith("COM") && this.PortName.Length > 3) { int number; int.TryParse(this.PortName.Substring(3), out number); this.PortNumber = number; } else { if (!this.PortName.StartsWith("LPT")) { logger.AddDebugMessage( string.Format( "Unable to get port number for '{0}' / '{1}' with port name '{2}'", this.Name, this.DeviceID, this.PortName)); } } }
private byte[] GetIISStatus() { List <string> iisStatus = new List <string>(); try { { ManagementPath path = new ManagementPath(); path.Server = Environment.MachineName; path.NamespacePath = "root\\CIMV2"; path.RelativePath = "Win32_PerfFormattedData_W3SVC_WebService.Name='Cms2012'"; using (ManagementObject service = new ManagementObject(path)) { service.Get(); iisStatus.Add(string.Format("Current connections: {0}", service.GetPropertyValue("CurrentConnections"))); iisStatus.Add(string.Format("Maximum connections: {0}", service.GetPropertyValue("MaximumConnections"))); iisStatus.Add(string.Format("Service up time: {0} seconds", service.GetPropertyValue("ServiceUptime"))); iisStatus.Add(string.Format("Total bytes received: {0:N2}MB", (ulong)service.GetPropertyValue("TotalBytesReceived") / 1024.00M / 1024.00M)); iisStatus.Add(string.Format("Total bytes sent: {0:N2}MB", (ulong)service.GetPropertyValue("TotalBytesSent") / 1024.00M / 1024.00M)); } } { ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2"); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_PerfFormattedData_ASPNET4030319_ASPNETv4030319"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) { using (ManagementObjectCollection coll = searcher.Get()) { foreach (ManagementObject m in coll) { iisStatus.Add(string.Format("Request execution time: {0} ms", m["RequestExecutionTime"])); iisStatus.Add(string.Format("Request wait time: {0} ms", m["RequestWaitTime"])); iisStatus.Add(string.Format("Current requests : {0}", m["RequestsCurrent"])); iisStatus.Add(string.Format("Queued requests : {0}", m["RequestsQueued"])); iisStatus.Add(string.Format("Rejected requests : {0}", m["RequestsRejected"])); iisStatus.Add(string.Format("Disconnected requests : {0}", m["RequestsDisconnected"])); iisStatus.Add(string.Format("Application restarts: {0}", m["ApplicationRestarts"])); iisStatus.Add(string.Format("Raised error events : {0}", m["ErrorEventsRaised"])); iisStatus.Add(string.Format("Raised request error events : {0}", m["RequestErrorEventsRaised"])); iisStatus.Add(string.Format("Raised infrastructure error events : {0}", m["InfrastructureErrorEventsRaised"])); } } } } return(SerializeList(iisStatus)); } catch (Exception ex) { Logger.Get().Append(ex); } return(null); }
private static int GetBrightness() { if (CanAdjustBrightness) { return(100); } else { return((byte)(WmiMonitorBrightness?.GetPropertyValue("CurrentBrightness") ?? 0)); } }
public DiskInfo(ManagementObject disk) { PhysicalName = (string)disk.GetPropertyValue("Name"); Name = (string)disk.GetPropertyValue("Caption"); Model = (string)disk.GetPropertyValue("Model"); //todo Why is Windows returning small sizes? https://stackoverflow.com/questions/15051660 Length = (long)disk.GetUlong("Size"); SectorSize = disk.GetInt("BytesPerSector"); DisplaySize = Util.GetBytesReadable(Length); Partitions = (uint)disk.GetPropertyValue("Partitions"); Index = (uint)disk.GetPropertyValue("Index"); }
public UsbDeviceInfo(ManagementObject device) { PNPDeviceID = (string)device.GetPropertyValue("PNPDeviceID"); Description = (string)device.GetPropertyValue("Description"); DeviceID = (string)device.GetPropertyValue("DeviceID"); Name = (string)device.GetPropertyValue("Name"); Manufacturer = (string)device.GetPropertyValue("Manufacturer"); CreationClassName = (string)device.GetPropertyValue("CreationClassName"); Service = (string)device.GetPropertyValue("Service"); ClassGuid = (string)device.GetPropertyValue("ClassGuid"); CompatibleID = (string[])device.GetPropertyValue("CompatibleID"); HardwareID = (string[])device.GetPropertyValue("HardwareID"); }
public static MsiWmiInstance FromWmi(uint index, string propertyName, ManagementObject obj, Func <uint, bool> validator = null) { validator = validator ?? ((x) => { return(true); }); return(new MsiWmiInstance { Index = index, Value = Convert.ToUInt32(obj.GetPropertyValue(propertyName)), InstanceName = Convert.ToString(obj.GetPropertyValue(AdvancedModeModel.NAME_KEY)), IsActive = Convert.ToBoolean(obj.GetPropertyValue(AdvancedModeModel.ACTIVE_KEY)), AdditionalValidator = validator }); }
public static SerialPortInfo FromManagementObject(ManagementObject o) { try { var name = o.GetPropertyValue(nameof(Name)) as string; if (string.IsNullOrEmpty(name) || !Regex.IsMatch(name, @"\(COM\d+\)")) { return(null); } var deviceId = o.GetPropertyValue(nameof(DeviceID)) as string; var portName = Registry.GetValue($@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Enum\{deviceId}\Device Parameters", "PortName", "").ToString(); return(new SerialPortInfo() { Caption = o.GetPropertyValue(nameof(Caption)) as string, ClassGuid = o.GetPropertyValue(nameof(ClassGuid)) as string, Description = o.GetPropertyValue(nameof(Description)) as string, Manufacturer = o.GetPropertyValue(nameof(Manufacturer)) as string, PNPClass = o.GetPropertyValue(nameof(PNPClass)) as string, PNPDeviceID = o.GetPropertyValue(nameof(PNPDeviceID)) as string, Name = name, DeviceID = deviceId, PortName = portName }); } catch { } return(null); }
public PerformanceSetting GetPerformanceSetting() { try { ManagementObjectCollection virtualSystemSettings = virtualMachine.GetRelated("Msvm_SummaryInformation"); ManagementObject virtualSystemSetting = WmiUtilities.GetFirstObjectFromCollection(virtualSystemSettings); //Msvm_SummaryInformation performanceSetting.Name = virtualSystemSetting.GetPropertyValue("Name") + ""; performanceSetting.ElementName = virtualSystemSetting.GetPropertyValue("ElementName") + ""; performanceSetting.InstanceID = virtualSystemSetting.GetPropertyValue("InstanceID") + ""; performanceSetting.NumberOfProcessors = Convert.ToUInt16(virtualSystemSetting.GetPropertyValue("NumberOfProcessors")); performanceSetting.EnabledState = Convert.ToUInt16(virtualSystemSetting.GetPropertyValue("EnabledState")); performanceSetting.HealthState = Convert.ToUInt16(virtualSystemSetting.GetPropertyValue("HealthState")); performanceSetting.ProcessorLoad = Convert.ToUInt16(virtualSystemSetting.GetPropertyValue("ProcessorLoad")); UInt16[] ProcessorHistoryInfo = (UInt16[])virtualSystemSetting.GetPropertyValue("ProcessorLoadHistory"); performanceSetting.ProcessorLoadHistory = ProcessorHistoryInfo; performanceSetting.MemoryUsage = Convert.ToUInt64(virtualSystemSetting.GetPropertyValue("MemoryUsage")); performanceSetting.GuestOperatingSystem = virtualSystemSetting.GetPropertyValue("GuestOperatingSystem") + ""; //performanceSetting.AvailableMemoryBuffer = Convert.ToInt32(virtualSystemSetting.GetPropertyValue("AvailableMemoryBuffer")); using (ManagementObject detailVMSetting = WmiUtilities.GetVirtualMachineSettings(virtualMachine)) { using (ManagementObjectCollection processorSettingDatas = detailVMSetting.GetRelated("Msvm_ProcessorSettingData")) using (ManagementObject processorSettingData = WmiUtilities.GetFirstObjectFromCollection(processorSettingDatas)) { performanceSetting.CPU_Reservation = Convert.ToUInt64(processorSettingData.GetPropertyValue("Reservation")); performanceSetting.CPU_Limit = Convert.ToUInt64(processorSettingData.GetPropertyValue("Limit")); performanceSetting.CPU_Weight = Convert.ToUInt32(processorSettingData.GetPropertyValue("Weight")); } using (ManagementObjectCollection memorySettingDatas = detailVMSetting.GetRelated("Msvm_MemorySettingData")) using (ManagementObject memorySettingData = WmiUtilities.GetFirstObjectFromCollection(memorySettingDatas)) { performanceSetting.RAM_VirtualQuantity = Convert.ToUInt64(memorySettingData.GetPropertyValue("VirtualQuantity")); performanceSetting.RAM_Weight = Convert.ToUInt32(memorySettingData.GetPropertyValue("Weight")); performanceSetting.RAM_DynamicMemoryEnabled = Convert.ToBoolean(memorySettingData.GetPropertyValue("DynamicMemoryEnabled")); } } performanceSetting.GuestCpuRatio = (((float)performanceSetting.CPU_Limit / 100000) * performanceSetting.NumberOfProcessors); performanceSetting.GuestCpuRatio = performanceSetting.GuestCpuRatio / 8; return(performanceSetting); } catch (Exception exp) { return(performanceSetting); } }
DisplayPoolResourceAllocationSettingData( ManagementScope scope, ManagementObject pool) { using (ManagementObject rasd = MsvmResourceAllocationSettingData.GetAllocationSettingsForPool( scope, pool.GetPropertyValue("ResourceType").ToString(), pool.GetPropertyValue("ResourceSubType").ToString(), pool.GetPropertyValue("PoolId").ToString())) { DisplayPoolResourceAllocationSettingData(rasd); } }
public DataClasses.SystemInfo GetSystemInfo() { DataClasses.SystemInfo systeminfo = new DataClasses.SystemInfo(); // Run queries for the four relevant WMI classes ManagementObject computerSystem = (connection.RunQuery("SELECT Name, SystemType, ChassisSKUNumber, Manufacturer, Model, Domain, TotalPhysicalMemory FROM Win32_ComputerSystem"))[0]; ManagementObject operatingSystem = (connection.RunQuery("SELECT Caption, CSName, LastBootUpTime, InstallDate, BuildNumber, Version, " + "CurrentTimeZone, OSLanguage, BootDevice, SystemDirectory, TotalVirtualMemorySize FROM Win32_OperatingSystem"))[0]; ManagementObject bios = (connection.RunQuery("SELECT Version, SerialNumber FROM Win32_Bios"))[0]; ManagementObject perfOSMem = (connection.RunQuery("SELECT AvailableMBytes, CommittedBytes, CommitLimit FROM Win32_PerfFormattedData_PerfOS_Memory"))[0]; ManagementObject timeZone = (connection.RunQuery("SELECT StandardName FROM win32_Timezone"))[0]; // Format data and assign to return object systeminfo.AvailableMemory = perfOSMem.GetPropertyValue("AvailableMBytes")?.ToString() ?? "" + "MB"; systeminfo.BiosVersion = bios.GetPropertyValue("Version")?.ToString() ?? ""; systeminfo.BootDevice = operatingSystem.GetPropertyValue("BootDevice")?.ToString() ?? ""; string boot = operatingSystem.GetPropertyValue("LastBootUpTime")?.ToString() ?? ""; if (boot != null) { systeminfo.BootTime = ManagementDateTimeConverter.ToDateTime(boot).ToString("MM/dd/yyyy hh:mm:ss tt"); } systeminfo.ChassisType = computerSystem.GetPropertyValue("ChassisSKUNumber")?.ToString() ?? ""; systeminfo.CommitLimit = ((UInt64)(perfOSMem.GetPropertyValue("CommitLimit")) / 1048576).ToString() + "MB"; systeminfo.Committed = ((UInt64)(perfOSMem.GetPropertyValue("CommittedBytes")) / 1048576).ToString() + "MB"; systeminfo.Domain = computerSystem.GetPropertyValue("Domain")?.ToString() ?? ""; systeminfo.InUseMemory = (((UInt64)(computerSystem.GetPropertyValue("TotalPhysicalMemory")) - (UInt64)(perfOSMem.GetPropertyValue("AvailableMBytes"))) / 1048576).ToString() + "MB"; string install = operatingSystem.GetPropertyValue("InstallDate")?.ToString() ?? ""; if (install != null) { systeminfo.InstallDate = ManagementDateTimeConverter.ToDateTime(install).ToString("MM/dd/yyyy hh:mm:ss tt"); } systeminfo.Language = operatingSystem.GetPropertyValue("OSLanguage")?.ToString() ?? ""; systeminfo.Manufacturer = computerSystem.GetPropertyValue("Manufacturer")?.ToString() ?? ""; systeminfo.Model = computerSystem.GetPropertyValue("Model")?.ToString() ?? ""; systeminfo.OS = operatingSystem.GetPropertyValue("Caption")?.ToString() ?? ""; systeminfo.OSBuild = operatingSystem.GetPropertyValue("BuildNumber")?.ToString() ?? ""; systeminfo.OSVersion = operatingSystem.GetPropertyValue("Version")?.ToString() ?? ""; systeminfo.SerialNumber = bios.GetPropertyValue("SerialNumber")?.ToString() ?? ""; systeminfo.SysName = operatingSystem.GetPropertyValue("CSName")?.ToString() ?? ""; systeminfo.SystemDir = operatingSystem.GetPropertyValue("SystemDirectory")?.ToString() ?? ""; systeminfo.SystemType = computerSystem.GetPropertyValue("SystemType")?.ToString() ?? ""; systeminfo.TimeZone = timeZone.GetPropertyValue("StandardName")?.ToString() ?? ""; systeminfo.TotalPhysicalMemory = ((UInt64)(computerSystem.GetPropertyValue("TotalPhysicalMemory")) / 1048576).ToString() + "MB"; systeminfo.TotalVirtualMemory = ((UInt64)(operatingSystem.GetPropertyValue("TotalVirtualMemorySize")) / 1048576).ToString() + "MB"; return(systeminfo); }
public static void StorageInfo() { ManagementPath path = new ManagementPath() { NamespacePath = @"root\cimv2", //Server = "<REMOTE HOST OR IP>" Server = "<192.168.1.111>" }; ManagementScope scope = new ManagementScope(path); string condition = "DriveLetter = 'C:'"; string[] selectedProperties = new string[] { "FreeSpace" }; SelectQuery query = new SelectQuery("Win32_Volume", condition, selectedProperties); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) using (ManagementObjectCollection results = searcher.Get()) { ManagementObject volume = results.Cast <ManagementObject>().SingleOrDefault(); if (volume != null) { ulong freeSpace = (ulong)volume.GetPropertyValue("FreeSpace"); // Use freeSpace here... } } }
DisplayPoolResourcePoolSettingData( string resourceDisplayName, string poolId) { Console.WriteLine( "Displaying the Msvm_ResourcePoolSettingData properties for the following " + "resource pool:\n" + "\tPool Id: " + poolId); ResourceUtilities.DisplayResourceInformation(resourceDisplayName); ManagementScope scope = ResourcePoolUtilities.GetManagementScope(); using (ManagementObject rpsd = MsvmResourcePoolSettingData.GetPoolResourcePoolSettingData( scope, ResourceUtilities.GetResourceType(resourceDisplayName), ResourceUtilities.GetResourceSubType(resourceDisplayName), poolId)) { Console.WriteLine("Msvm_ResourcePoolSettingData:"); Console.WriteLine("\tElementName: " + rpsd.GetPropertyValue("ElementName").ToString()); } }
/// <summary> /// 获取逻辑分区(C盘)序列号,重新格式化会改变 /// </summary> /// <returns></returns> private string GetDiskSerialNumber() { ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\""); disk.Get(); return(disk.GetPropertyValue("VolumeSerialNumber").ToString()); }
public void ListaServicio() { listVServicio.Items.Clear(); contCorr = 0; //cuenta los servicios corriendo. contSup = 0; //cuenta los servicios suspendidos. ServiceController[] scServices; scServices = ServiceController.GetServices(); //recupera todo los servicios. //se van ingresando los servicios a las listas. foreach (ServiceController scTemp in scServices) { listServicio = new ListViewItem(scTemp.ServiceName); //Nombre del servicio. ManagementObject service1 = new ManagementObject(@"Win32_service.Name='" + scTemp.ServiceName + "'"); listServicio.SubItems.Add(service1.GetPropertyValue("ProcessId").ToString()); //PID del servicio. // listServicio.SubItems.Add(""); listServicio.SubItems.Add(scTemp.DisplayName); //Descripcion del servicio. listServicio.SubItems.Add(scTemp.Status.ToString()); //estado del servicio. listServicio.SubItems.Add(scTemp.MachineName); //nombre del equipo donde reside el servicio. listServicio.SubItems.Add(scTemp.CanPauseAndContinue.ToString()); //se puede pausar o reanudar. listServicio.SubItems.Add(scTemp.CanStop.ToString()); //se puede detener el servicio. listVServicio.Items.Add(listServicio); if (scTemp.Status.ToString() == "Running") { contCorr = contCorr + 1; } else { contSup = contSup + 1; } Thread.Sleep(10); } }
public static string Win32_GetMainBoardBiosSerialNumber1() { ManagementObject managementObject = new ManagementObject("win32_logicaldisk.deviceid=\"d:\""); managementObject.Get(); return(managementObject.GetPropertyValue("VolumeSerialNumber").ToString()); }
//获得网卡序列号----MAc地址 public string GetMoAddress() { try { //读取硬盘序列号 ManagementObject disk; disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\""); disk.Get(); string MoAddress = "BD-CNSOFTWEB"; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc2 = mc.GetInstances(); foreach (ManagementObject mo in moc2) { if ((bool)mo["IPEnabled"] == true) { string a = mo["MacAddress"].ToString(); string c = disk.GetPropertyValue("VolumeSerialNumber").ToString(); MoAddress = "BD-" + a + "-" + c + "-CNSOFTWEB"; break; } } return MoAddress.ToString().Replace(":", ""); } catch { return "BD-ERR-CNSOFTWEB"; } }
//获得网卡序列号----MAc地址 public string GetMoAddress() { try { //读取硬盘序列号 ManagementObject disk; disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\""); disk.Get(); string MoAddress = "BD-CNSOFTWEB"; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc2 = mc.GetInstances(); foreach (ManagementObject mo in moc2) { if ((bool)mo["IPEnabled"] == true) { string a = mo["MacAddress"].ToString(); string c = disk.GetPropertyValue("VolumeSerialNumber").ToString(); MoAddress = "BD-" + a + "-" + c + "-CNSOFTWEB"; break; } } return(MoAddress.ToString().Replace(":", "")); } catch { return("BD-ERR-CNSOFTWEB"); } }
// Token: 0x060000BB RID: 187 RVA: 0x00009D5C File Offset: 0x00007F5C internal string GetVolumeSerial(string strDriveLetter = "C") { ManagementObject managementObject = new ManagementObject(string.Format("win32_logicaldisk.deviceid=\"{0}:\"", strDriveLetter)); managementObject.Get(); return(managementObject.GetPropertyValue("VolumeSerialNumber").ToString()); }
/// <summary> /// 取得设备硬盘的卷标号 /// </summary> /// <returns>硬盘的卷标号</returns> public string GetDiskVolumeSerialNumber() { _mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); _disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\""); _disk.Get(); return(_disk.GetPropertyValue("VolumeSerialNumber").ToString()); }
public static T Bind <T>(ManagementObject o) where T : IManagementObjectWrapper { if (!typeof(T).IsDefined(typeof(ManagementObjectAttribute))) { throw new ArgumentException("{T} must define the ManagementObjectAttribute attribute."); } var instance = (T)Activator.CreateInstance(typeof(T)); var members = typeof(T).GetMembers().Where(m => m.IsDefined(typeof(ManagementObjectPropertyAttribute))); foreach (var member in members) { if (member.Name == "BaseObject") { ((PropertyInfo)member).SetValue(instance, o); continue; } var mgmtPropertyAttr = member.GetCustomAttribute <ManagementObjectPropertyAttribute>(); var mgmtPropertyValue = o.GetPropertyValue(mgmtPropertyAttr.Name ?? member.Name); switch (member) { case FieldInfo field: field.SetValue(instance, mgmtPropertyValue); break; case PropertyInfo property: property.SetValue(instance, mgmtPropertyValue); break; } } return(instance); }
/// <summary> /// 获取机器号码 /// </summary> /// <returns></returns> public static string GetDiskCPUNumber() { string strDiskCPUNumber = ""; // 取得设备硬盘的卷标号 string strDisk = null; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\""); disk.Get(); strDisk = disk.GetPropertyValue("VolumeSerialNumber").ToString(); //获得CPU的序列号 string strCPU = null; ManagementClass myCpu = new ManagementClass("win32_Processor"); ManagementObjectCollection myCpuConnection = myCpu.GetInstances(); foreach (ManagementObject myObject in myCpuConnection) { strCPU = myObject.Properties["Processorid"].Value.ToString(); break; } return strDiskCPUNumber = strCPU + strDisk; }