System.Management.ManagementObjectSearcher.Get()

Here are the examples of the csharp api System.Management.ManagementObjectSearcher.Get() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2503 Examples 7

19 View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

public static void SendDiscovery(string CMServerName, string clientName, string domainName, string SiteCode,
            string CertPath, SecureString preplaced, SmsClientId clientId, ILog log, bool enumerateAndAddCustomDdr = false)
        {
            using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))

            {
                //X509Certificate2 thisCert = new X509Certificate2(CertPath, preplaced);

                log.Info($"Got SMSID from registration of: {clientId}");

                // create base DDR Message
                ConfigMgrDataDiscoveryRecordMessage ddrMessage = new ConfigMgrDataDiscoveryRecordMessage
                {
                    // Add necessary discovery data
                    SmsId = clientId,
                    ADSiteName = "Default-First-Site-Name", //Changed from 'My-AD-SiteName
                    SiteCode = SiteCode,
                    DomainName = domainName,
                    NetBiosName = clientName
                };

                ddrMessage.Discover();
                // Add our certificate for message signing
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing);
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Encryption);
                ddrMessage.Settings.HostName = CMServerName;
                ddrMessage.Settings.Compression = MessageCompression.Zlib;
                ddrMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                Debug.WriteLine("Sending [" + ddrMessage.DdrInstances.Count + "] instances of Discovery data to CM");
                if (enumerateAndAddCustomDdr)
                {
                    //see current value for the DDR message
                    var OSSetting = ddrMessage.DdrInstances.OfType<InventoryInstance>().Where(m => m.Clreplaced == "CCM_DiscoveryData");

                    ////retrieve actual setting
                    string osCaption = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
                                        select x.GetPropertyValue("Caption")).FirstOrDefault().ToString();

                    XmlDoreplacedent xmlDoc = new XmlDoreplacedent();

                    ////retrieve reported value
                    xmlDoc.LoadXml(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData")?.InstanceDataXml.ToString());

                    ////Set OS to correct setting
                    xmlDoc.SelectSingleNode("/CCM_DiscoveryData/PlatformID").InnerText = "Microsoft Windows NT Server 10.0";

                    ////Remove the instance
                    ddrMessage.DdrInstances.Remove(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData"));

                    CMFauxStatusViewClreplacedesFixedOSRecord FixedOSRecord = new CMFauxStatusViewClreplacedesFixedOSRecord
                    {
                        PlatformId = osCaption
                    };
                    InventoryInstance instance = new InventoryInstance(FixedOSRecord);

                    ////Add new instance
                    ddrMessage.DdrInstances.Add(instance);
                }

                ddrMessage.SendMessage(Sender);

                ConfigMgrHardwareInventoryMessage hinvMessage = new ConfigMgrHardwareInventoryMessage();
                hinvMessage.Settings.HostName = CMServerName;
                hinvMessage.SmsId = clientId;
                hinvMessage.Settings.Compression = MessageCompression.Zlib;
                hinvMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                //hinvMessage.Settings.Security.EncryptMessage = true;
                hinvMessage.Discover();

                var Clreplacedes = CMFauxStatusViewClreplacedes.GetWMIClreplacedes();
                foreach (string Clreplaced in Clreplacedes)
                {
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                var SMSClreplacedes = new List<string> { "SMS_Processor", "CCM_System", "SMS_LogicalDisk" };
                foreach (string Clreplaced in SMSClreplacedes)
                {
                    log.Info($"---Adding clreplaced : [{Clreplaced}]");
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2\sms", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                hinvMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
                hinvMessage.Validate(Sender);
                hinvMessage.SendMessage(Sender);
            };
        }

19 View Source File : SettingsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private void ComboBoxSerialPort_DropDownOpened(object sender, EventArgs e)
		{
			ComboBoxSerialPort.Items.Clear();

			Dictionary<string, string> ports = new Dictionary<string, string>();

			try
			{
				ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort");
				foreach (ManagementObject queryObj in searcher.Get())
				{
					string id = queryObj["DeviceID"] as string;
					string name = queryObj["Name"] as string;

					ports.Add(id, name);
				}
			}
			catch (ManagementException ex)
			{
				MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
			}

			// fix error of some boards not being listed properly
			foreach (string port in SerialPort.GetPortNames())
			{
				if (!ports.ContainsKey(port))
				{
					ports.Add(port, port);
				}
			}

			foreach (var port in ports)
			{
				ComboBoxSerialPort.Items.Add(new ComboBoxItem() { Content = port.Value, Tag = port.Key });
			}
		}

19 View Source File : SerialBusManager.cs
License : GNU General Public License v3.0
Project Creator : a4004

private static string GetDeviceName(string comPort)
        {
            try
            {
                string result = new ManagementObjectSearcher("Select * from Win32_SerialPort")
                    .Get().OfType<ManagementObject>()
                    .Where(o => comPort.Equals(o["DeviceID"]))
                    .First().Properties.OfType<PropertyData>()
                    .Where(t => t.Name.Equals("Description"))
                    .First().Value as string;

                return result;
            }
            catch
            {
                return $"Unknown device ({comPort})";
            }
        }

19 View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private static bool ExecuteCommand(ref byte[] buffer)
        {
            bool result = false;

            if (buffer.Length < MinimumBufferLength)
            {
                throw new Exception(string.Format("Buffer length is less than the minimum {0} bytes", MinimumBufferLength));
            }

            ManagementBaseObject instance = new ManagementClreplaced(WmiScopeRoot, WmiClreplacedNameBdat, null).CreateInstance();
            instance["Bytes"] = buffer;

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(new ManagementScope(WmiScopeRoot), new SelectQuery(WmiClreplacedNameBfn))
            {
                Options = new EnumerationOptions()
                {
                    EnsureLocatable = true
                }
            };

            foreach (ManagementObject managementObject in searcher.Get())
            {
                if (managementObject["InstanceName"].ToString().ToUpper().Equals(AcpiManagementInterfaceHardwareId))
                {
                    ManagementBaseObject methodParameters = managementObject.GetMethodParameters(WmiBfnMethodDobfn);
                    methodParameters["Data"] = instance;
                    ManagementBaseObject managementBaseObject = (ManagementBaseObject)managementObject.InvokeMethod(WmiBfnMethodDobfn, methodParameters, null).Properties["Data"].Value;
                    buffer = (byte[])managementBaseObject["Bytes"];
                    result = true;
                    break;
                }
            }

            return result;
        }

19 View Source File : WmiFanSpeedReader.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

public FanSpeeds GetFanSpeeds()
        {
            uint? rpm1 = null;
            uint? rpm2 = null;

            if (FanSensor1Searcher != null)
            {
                foreach (ManagementObject fanSensor in FanSensor1Searcher.Get())
                {
                    if (uint.TryParse(fanSensor.GetPropertyValue("CurrentReading")?.ToString(), out uint value))
                    {
                        rpm1 = value;
                    }
                    break;
                }
            }

            if (FanSensor2Searcher != null)
            {
                foreach (ManagementObject fanSensor in FanSensor2Searcher.Get())
                {
                    if (uint.TryParse(fanSensor.GetPropertyValue("CurrentReading")?.ToString(), out uint value))
                    {
                        rpm2 = value;
                    }
                    break;
                }
            }

            return new FanSpeeds()
            {
                Fan1Rpm = rpm1,
                Fan2Rpm = rpm2
            };
        }

19 View Source File : Local.cs
License : Apache License 2.0
Project Creator : aequabit

private static string getProperty(string component, string property)
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", String.Format("SELECT {0} FROM {1}", property, component));
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    return queryObj[property].ToString();
                }
            }
            catch
            {
            }
            return "";
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AhmedMinegames

public static string GetHardwareID()
        {
            ManagementObjectSearcher CPU = new ManagementObjectSearcher(UTF8Encoding.UTF8.GetString(Convert.FromBase64String("U0VMRUNUICogRlJPTSBXaW4zMl9Qcm9jZXNzb3I=")));
            ManagementObjectCollection GetCPU = CPU.Get();
            string CPUID = null;
            foreach (ManagementObject CPUId in GetCPU)
            {
                CPUID = CPUId[UTF8Encoding.UTF8.GetString(Convert.FromBase64String("UHJvY2Vzc29yVHlwZQ=="))].ToString() + CPUId[UTF8Encoding.UTF8.GetString(Convert.FromBase64String("UHJvY2Vzc29ySWQ="))].ToString();
            }
            ManagementObjectSearcher BIOS = new ManagementObjectSearcher(UTF8Encoding.UTF8.GetString(Convert.FromBase64String("U0VMRUNUICogRlJPTSBXaW4zMl9CSU9T")));
            ManagementObjectCollection GetBIOS = BIOS.Get();
            string GPUID = null;
            foreach (ManagementObject BIOSId in GetBIOS)
            {
                GPUID = BIOSId["Manufacturer"].ToString() + BIOSId["Version"].ToString();
            }
            return HashingHardwareID(CPUID + GPUID);
        }

19 View Source File : USBPacker.cs
License : MIT License
Project Creator : AhmedMinegames

private static string GetUSBHardwareID()
        {
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                if (drive.DriveType == DriveType.Removable)
                {
                    foreach (ManagementObject managementObject in new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive").Get())
                    {
                        if (managementObject["MediaType"].ToString() == "Removable Media")
                            return Program.HashingHardwareID(drive.TotalSize.ToString() + managementObject["SerialNumber"].ToString() + managementObject["PNPDeviceID"].ToString());
                    }
                }
            }
            return (string)null;
        }

19 View Source File : Main.cs
License : MIT License
Project Creator : AhmedMinegames

private static string GetHardwareID()
        {
            ManagementObjectSearcher CPU = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
            ManagementObjectCollection GetCPU = CPU.Get();
            string CPUID = null;
            foreach (ManagementObject CPUId in GetCPU)
            {
                CPUID = CPUId["ProcessorType"].ToString() + CPUId["ProcessorId"].ToString();
            }
            ManagementObjectSearcher BIOS = new ManagementObjectSearcher("SELECT * FROM Win32_BIOS");
            ManagementObjectCollection GetBIOS = BIOS.Get();
            string GPUID = null;
            foreach (ManagementObject BIOSId in GetBIOS)
            {
                GPUID = BIOSId["Manufacturer"].ToString() + BIOSId["Version"].ToString();
            }
            return HashingHardwareID(CPUID + GPUID);
        }

19 View Source File : Main.cs
License : MIT License
Project Creator : AhmedMinegames

private static string GetUSBHardwareID(string USBPath)
        {
            DriveInfo[] GetDrives = DriveInfo.GetDrives();
            foreach (DriveInfo GetInfo in GetDrives)
            {
                if (GetInfo.RootDirectory.ToString() == USBPath)
                {
                    ManagementObjectSearcher USB = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
                    ManagementObjectCollection GetUSB = USB.Get();
                    foreach (ManagementObject USBHardwareID in GetUSB)
                    {
                        if (USBHardwareID["MediaType"].ToString() == "Removable Media")
                        {
                            return HashingHardwareID(GetInfo.TotalSize + USBHardwareID["SerialNumber"].ToString() + USBHardwareID["PNPDeviceID"].ToString());
                        }
                    }
                }
            }
            return null;
        }

19 View Source File : MachineInfo.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private string[] SelectProperties(string clsName, string propName)
		{
			List<string> props = new List<string>();
			try
			{
				string wql = string.Format("SELECT * FROM {0}", clsName);
				using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", wql))
				{
					foreach (var mo in searcher.Get())
						props.Add((mo[propName] ?? "").ToString());
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
			return props.ToArray();
		}

19 View Source File : MachineInfo.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private string GetMainDriverModel()
		{
			string model = null;
			try
			{
				string wql = string.Format("SELECT * FROM {0}", @"Win32_DiskDrive");
				using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", wql))
				{
					foreach (var mo in searcher.Get())
					{
						string deviceId = (mo["DeviceID"]).ToString();
						if (deviceId != null && deviceId.EndsWith("PHYSICALDRIVE0"))
						{
							model = (mo["Model"] ?? "").ToString();
							break;
						}
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
			return model;
		}

19 View Source File : MachineInfo.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private string[] SelectProperties(string clsName, string propName)
		{
			List<string> props = new List<string>();
			try
			{
				string wql = string.Format("SELECT * FROM {0}", clsName);
				using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", wql))
				{
					foreach (var mo in searcher.Get())
						props.Add((mo[propName] ?? "").ToString());
				}
			}
			catch (Exception ex) { TraceLog.WriteException(ex); }
			return props.ToArray();
		}

19 View Source File : ApplicationAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public ApplicationInfo[] GetInstalledApplications()
		{
			List<ApplicationInfo> apps = new List<ApplicationInfo>();
			try
			{
				string wql = @"SELECT * FROM Win32_Product WHERE InstallLocation IS NOT NULL";
				using (var searcher = new ManagementObjectSearcher("root\\CIMV2", wql))
				{
					foreach (var mo in searcher.Get())
					{
						var app = new ApplicationInfo()
						{
							Name = Convert.ToString(mo["Name"]),
							Version = Convert.ToString(mo["Version"]),
							Description = Convert.ToString(mo["Description"]),
							Location = Convert.ToString(mo["InstallLocation"]),
							InstallDate = DateTime.ParseExact(Convert.ToString(mo["InstallDate"]),"yyyyMMdd", null)
						};
						apps.Add(app);
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return apps.ToArray();
		}

19 View Source File : SystemUserAccess.cs
License : GNU General Public License v3.0
Project Creator : aiportal

[Obsolete]
		public string[] GetUserGroupsByWMI(string userName)
		{
			List<string> groups = new List<string>();
			try
			{
				Regex regGroupName = new Regex(",Name=\"(?<group>.+)\"");
				string wql = string.Format("SELECT * FROM Win32_GroupUser WHERE PartComponent=\"Win32_UserAccount.Domain='{0}',Name='{1}'\"", Environment.UserDomainName, userName);
				using (var searcher = new ManagementObjectSearcher("root\\CIMV2", wql))
				{
					foreach (var mo in searcher.Get())
					{
						string val = Convert.ToString(mo["GroupComponent"]);
						var mc = regGroupName.Match(val);
						if (mc.Success)
							groups.Add(mc.Groups["group"].Value);
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return groups.ToArray();
		}

19 View Source File : MachineInfo.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private string GetMainDriverModel()
		{
			string model = null;
			try
			{
				string wql = string.Format("SELECT * FROM {0}", @"Win32_DiskDrive");
				using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", wql))
				{
					foreach (var mo in searcher.Get())
					{
						string deviceId = (mo["DeviceID"]).ToString();
						if (deviceId != null && deviceId.EndsWith("PHYSICALDRIVE0"))
						{
							model = (mo["Model"] ?? "").ToString();
							break;
						}
					}
				}
			}
			catch (Exception ex) { TraceLog.WriteException(ex); }
			return model;
		}

19 View Source File : WindowUtils.cs
License : MIT License
Project Creator : AlexanderPro

private static string GetProcessName(int processId)
        {
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Process WHERE ProcessId = " + processId))
            using (var objects = searcher.Get())
            {
                var baseObject = objects.Cast<ManagementBaseObject>().FirstOrDefault();
                if (baseObject != null)
                {
                    return baseObject["ExecutablePath"] != null ? baseObject["ExecutablePath"].ToString() : "";
                }
                return "";
            }
        }

19 View Source File : SystemUtils.cs
License : MIT License
Project Creator : AlexanderPro

public static WmiProcessInfo GetWmiProcessInfo(int processId)
        {
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Process WHERE ProcessId = " + processId))
            using (var objects = searcher.Get())
            {
                var processInfo = new WmiProcessInfo();
                foreach (ManagementObject obj in objects)
                {
                    var argList = new string[] { string.Empty, string.Empty };
                    var returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
                    if (returnVal == 0)
                    {
                        // return DOMAIN\user
                        processInfo.Owner = argList[1] + "\\" + argList[0];
                        break;
                    }
                }

                var baseObject = objects.Cast<ManagementBaseObject>().FirstOrDefault();
                if (baseObject != null)
                {
                    processInfo.CommandLine = baseObject["CommandLine"] != null ? baseObject["CommandLine"].ToString() : "";
                    processInfo.HandleCount = baseObject["HandleCount"] != null ? (uint)baseObject["HandleCount"] : 0;
                    processInfo.ThreadCount = baseObject["ThreadCount"] != null ? (uint)baseObject["ThreadCount"] : 0;
                    processInfo.VirtualSize = baseObject["VirtualSize"] != null ? (ulong)baseObject["VirtualSize"] : 0;
                    processInfo.WorkingSetSize = baseObject["WorkingSetSize"] != null ? (ulong)baseObject["WorkingSetSize"] : 0;
                }

                return processInfo;
            }
        }

19 View Source File : WindowUtils.cs
License : MIT License
Project Creator : AlexanderPro

private static WmiProcessInfo GetWmiProcessInfo(int pId)
        {
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Process WHERE ProcessId = " + pId))
            using (var objects = searcher.Get())
            {
                var processInfo = new WmiProcessInfo();
                foreach (ManagementObject obj in objects)
                {
                    var argList = new string[] { string.Empty, string.Empty };
                    var returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
                    if (returnVal == 0)
                    {
                        // return DOMAIN\user
                        processInfo.Owner = argList[1] + "\\" + argList[0];
                        break;
                    }
                }

                var baseObject = objects.Cast<ManagementBaseObject>().FirstOrDefault();
                if (baseObject != null)
                {
                    processInfo.CommandLine = baseObject["CommandLine"] != null ? baseObject["CommandLine"].ToString() : "";
                    processInfo.HandleCount = baseObject["HandleCount"] != null ? (uint)baseObject["HandleCount"] : 0;
                    processInfo.ThreadCount = baseObject["ThreadCount"] != null ? (uint)baseObject["ThreadCount"] : 0;
                    processInfo.VirtualSize = baseObject["VirtualSize"] != null ? (ulong)baseObject["VirtualSize"] : 0;
                    processInfo.WorkingSetSize = baseObject["WorkingSetSize"] != null ? (ulong)baseObject["WorkingSetSize"] : 0;
                }

                return processInfo;
            }
        }

19 View Source File : WindowsSmart.cs
License : MIT License
Project Creator : AlexGyver

public string[] GetLogicalDrives(int driveIndex) {
      List<string> list = new List<string>();
      try {
        using (ManagementObjectSearcher s = new ManagementObjectSearcher(
            "root\\CIMV2",
            "SELECT * FROM Win32_DiskParreplacedion " +
            "WHERE DiskIndex = " + driveIndex))
        using (ManagementObjectCollection dpc = s.Get())
        foreach (ManagementObject dp in dpc) 
          using (ManagementObjectCollection ldc = 
            dp.GetRelated("Win32_LogicalDisk"))
          foreach (ManagementBaseObject ld in ldc) 
            list.Add(((string)ld["Name"]).TrimEnd(':')); 
      } catch { }
      return list.ToArray();
    }

19 View Source File : Volumes.cs
License : MIT License
Project Creator : alexis-

public static List<Volume> ListVolumes()
    {
      List<Volume> volumes = new List<Volume>();

      ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Volume");
      ManagementObjectCollection collection = searcher.Get();

      foreach (ManagementObject item in collection)
        volumes.Add(new Volume()
        {
          Name = (string)item["Name"],
          Label = (string)item["Label"],
          MountLetter = (string)item["DriveLetter"],
          DeviceID = (string)item["DeviceID"]
        });

      return volumes;
    }

19 View Source File : Resume.cs
License : MIT License
Project Creator : Alkl58

public static List<int> GetChildProcesses(int process_id)
        {
            List<int> children = new List<int>();

            ManagementObjectSearcher mos = new ManagementObjectSearcher(String.Format("Select * From Win32_Process Where ParentProcessID={0}", process_id));

            foreach (ManagementObject mo in mos.Get())
            {
                children.Add(Convert.ToInt32(mo["ProcessID"]));
            }

            return children;
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : Alkl58

public static int GetCoreCount()
        {
            // Gets Core Count
            int coreCount = 0;
            foreach (System.Management.ManagementBaseObject item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
            {
                coreCount += int.Parse(item["NumberOfCores"].ToString());
            }
            return coreCount;
        }

19 View Source File : ProcessFilter.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx

public IEnumerable<int> GetMatchingPids()
        {
            string query = "SELECT Name, CommandLine, ProcessId FROM Win32_Process";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            foreach (ManagementObject mo in searcher.Get())
            {
                string exename = (string) mo["Name"];
                string cmdLine = (string) mo["CommandLine"];
                int pid = (int) (UInt32) mo["ProcessId"];

                if( CmdLineFilters != null )
                {
                    if( String.IsNullOrEmpty(cmdLine) )
                    {
                        continue;
                    }

                    foreach(var cmdLineFilter in CmdLineFilters)
                    {
                        if (cmdLine.IndexOf(cmdLineFilter, StringComparison.OrdinalIgnoreCase) == -1)
                        {
                            goto Continue;
                        }

                    }
                }

                if( PidFilter != 0 )
                {
                    if( PidFilter != pid)
                    {
                        continue;
                    }
                }

                if( !String.IsNullOrEmpty(ProcessNameFilter)  )
                {
                    if( String.Compare(ProcessNameFilter, exename, StringComparison.OrdinalIgnoreCase) != 0 )
                    {
                        continue;
                    }
                }

                yield return pid;

            Continue:
                ;
            }
        }

19 View Source File : WmiQuery.cs
License : GNU General Public License v3.0
Project Creator : Alois-xx

public void Execute()
        { 
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(myWmiNamespace, myQuery);

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    foreach(var prop in queryObj.Properties)
                    {
                        Console.WriteLine($"[{prop.Name}]: {prop.Value}");
                    }
                }
            }
            catch (ManagementException e)
            {

            }
        }

19 View Source File : ProcessFilter.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx

public static string GetProcessCommandLine(int pid)
        {
            string query = $"SELECT Name, CommandLine, ProcessId FROM Win32_Process WHERE ProcessId='{pid}'";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            foreach(ManagementObject mo in searcher.Get())
            {
                return (string)mo["CommandLine"] ?? "";
            }

            return "";
        }

19 View Source File : DNSChallengeWinDnsValidator.cs
License : GNU General Public License v3.0
Project Creator : aloopkin

public bool PrepareChallengeForValidation(string dnsKeyName, string dnsKeyValue)
        {
            ManagementScope mgmtScope = new ManagementScope(@"\\" + DNSServerHost + @"\Root\MicrosoftDNS");
            if (DNSServerUser != null) mgmtScope.Options = LoginOptions();
            mgmtScope.Connect();

            ManagementObjectSearcher mgmtSearch = new ManagementObjectSearcher(mgmtScope, new ObjectQuery(string.Format("SELECT * FROM MicrosoftDNS_TXTType WHERE OwnerName = '{0}'", dnsKeyName)));
            ManagementObjectCollection mgmtDNSRecords = mgmtSearch.Get();

            if (mgmtDNSRecords.Count >= 1) {
                foreach (ManagementObject mgmtDNSRecord in mgmtDNSRecords) {
                    ManagementBaseObject mgmtParams = mgmtDNSRecord.GetMethodParameters("Modify");
                    mgmtParams["DescriptiveText"] = dnsKeyValue;
                    mgmtDNSRecord.InvokeMethod("Modify", mgmtParams, null);
                    break;
                }
                logger.Debug($"Updated DNS record of type [TXT] with name [{dnsKeyName}]");
                return true;
            } else if (mgmtDNSRecords.Count == 0) {
                ManagementClreplaced mgmtClreplaced = new ManagementClreplaced(mgmtScope, new ManagementPath("MicrosoftDNS_TXTType"), null);
                ManagementBaseObject mgmtParams = mgmtClreplaced.GetMethodParameters("CreateInstanceFromPropertyData");
                mgmtParams["DnsServerName"] = Environment.MachineName;
                if (DNSServerZone == null) DNSServerZone = dnsKeyName.Split('.')[dnsKeyName.Split('.').Count() - 2] + "." + dnsKeyName.Split('.')[dnsKeyName.Split('.').Count() - 1];
                mgmtParams["ContainerName"] = DNSServerZone;
                mgmtParams["OwnerName"] = dnsKeyName;
                mgmtParams["DescriptiveText"] = dnsKeyValue;
                mgmtClreplaced.InvokeMethod("CreateInstanceFromPropertyData", mgmtParams, null);
                logger.Debug($"Created DNS record of type [TXT] with name [{dnsKeyName}]");
                return true;
            }
            return false;
        }

19 View Source File : frmMain.cs
License : GNU General Public License v3.0
Project Creator : amakvana

private async Task GetGPUConfig(string yuzuLocation)
        {
            ToggleControls(false);

            // detect current GPU
            bool useOpenGL = false;
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["Name"].ToString().ToLower().Contains("nvidia"))
                    {
                        useOpenGL = true;
                    }
                }
            }

            // fetch optimised config based on installed GPU
            using (var wc = new WebClient())
            {
                // download it 
                wc.DownloadFileCompleted += (s, e) =>
                {
                    SetProgressLabelStatus("Done!");
                    ToggleControls(true);
                    pbarProgress.Value = 0;
                };
                wc.DownloadProgressChanged += Wc_DownloadProgressChanged;

                string gpuConfigUrl = "https://github.com/amakvana/EzYuzu/raw/master/configs/";
                gpuConfigUrl += (useOpenGL) ? "opengl.ini" : "vulkan.ini";
                SetProgressLabelStatus("Downloading Optimised GPU Config ...");
                await wc.DownloadFileTaskAsync(new Uri(gpuConfigUrl), yuzuLocation + "\\User\\config\\qt-config.ini");
            }
        }

19 View Source File : SystemManagement.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static string GetProcessCommandLine(int processId)
        {
            try
            {
                StringBuilder builder = new StringBuilder();
                using (var searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId=" + processId))
                {
                    bool firsreplacederation = true;
                    foreach (var @object in searcher.Get())
                    {
                        if (firsreplacederation)
                        {
                            firsreplacederation = false;
                        }
                        else
                        {
                            builder.Append(" ");
                        }
                        builder.Append(@object["CommandLine"]);
                    }
                }
                return builder.ToString();
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

19 View Source File : GetInjectedThreads.cs
License : MIT License
Project Creator : Apr4h

static string GetProcessOwner(int processId)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher($"Select * From Win32_Process Where ProcessID = {processId}");
            ManagementObjectCollection processList = searcher.Get();

            foreach(ManagementObject obj in processList)
            {
                string[] argList = new string[] { string.Empty, string.Empty };
                int result = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
                
                if(result == 0)
                {
                    return $"{argList[1]}\\{argList[0]}";
                }
            }
            return "NO OWNER";
        }

19 View Source File : GetInjectedThreads.cs
License : MIT License
Project Creator : Apr4h

static string GetProcessCommandLine(Process process)
        {
            string commandLine = null;

            try
            {
                // Requres reference to System.Management.dll replacedembly for WMI clreplaced
                using (var searcher = new ManagementObjectSearcher($"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {process.Id}"))
                {
                    using (var matchEnum = searcher.Get().GetEnumerator())
                    {
                        if (matchEnum.MoveNext())
                        {
                            commandLine = matchEnum.Current["CommandLine"]?.ToString();
                        }
                    }
                }
            }
            // Catch process exited exception
            catch(InvalidOperationException) 
            {
                Console.WriteLine($"Couldn't get CommandLine for PID {process.Id} - Process has exited");
            }

            return commandLine;
        }

19 View Source File : SPLHelper.cs
License : GNU General Public License v3.0
Project Creator : ArduinoIoTDev

public static string GetSPLDuinoComPortName()
        {
            string com_port = string.Empty;

            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEnreplacedy");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (queryObj != null)
                    {
                        object q_obj = queryObj["Caption"];

                        if (q_obj != null)
                        {
                            string caption_str = q_obj.ToString();
                            if (!string.IsNullOrEmpty(caption_str))
                            {
                                if (caption_str.Contains("(COM"))
                                {
                                    if (caption_str.Contains("Silicon") && caption_str.Contains("UART Bridge"))
                                    {
                                        int pos = caption_str.IndexOf("(COM");
                                        string desc = caption_str.Substring(pos + 1);

                                        desc = desc.Trim();
                                        desc = desc.TrimEnd(')');

                                        return desc;
                                    }
                                }
                            }

                        }
                    }

                }
            }
            catch
            {
                
            }

            return com_port;
        }

19 View Source File : SPLHelper.cs
License : GNU General Public License v3.0
Project Creator : ArduinoIoTDev

public static List<string> GetComPortNameList()
        {
            List<string> com_port_list = new List<string>();

            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEnreplacedy");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (queryObj != null)
                    {
                        object q_obj = queryObj["Caption"];

                        if (q_obj != null)
                        {
                            string caption_str = q_obj.ToString();
                            string caption_str_lower = caption_str.ToLower();

                            if (!string.IsNullOrEmpty(caption_str))
                            {
                                if (caption_str.Contains("(COM"))
                                {
                                    int pos = caption_str.IndexOf("(COM");
                                    string port_name = caption_str.Substring(pos + 1);

                                    port_name = port_name.Trim();
                                    port_name = port_name.TrimEnd(')');

                                    if (caption_str.Contains("CH340"))
                                        port_name = port_name + " (SPL-Duino V2)";
                                    else if (caption_str.Contains("Silicon") && caption_str.Contains("UART Bridge"))
                                        port_name = port_name + " (SPL-Duino V1)";
                                    else if (caption_str_lower.Contains("bluetooth"))
                                        port_name = port_name + " (Bluetooth)";

                                    com_port_list.Add(port_name);
                                }
                            }

                        }
                    }

                }
            }
            catch
            {

            }

            return com_port_list;
        }

19 View Source File : SPLHelper.cs
License : GNU General Public License v3.0
Project Creator : ArduinoIoTDev

public static List<string> GetComPortList()
        {
            List<string> com_port_list = new List<string>();

            ManagementScope connectionScope = new ManagementScope();
            SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery);

            try
            {
                foreach (ManagementObject item in searcher.Get())
                {
                    string desc = item["Description"].ToString();
                    string deviceId = item["DeviceID"].ToString();

                    if (desc.Contains("Silicon") && desc.Contains("UART Bridge"))
                    {
                        string com_port = deviceId;
                        com_port_list.Add(com_port);
                    }


                }
            }
            catch (ManagementException ex)
            {
                /* Do Nothing */
            }

            return com_port_list;
        }

19 View Source File : MinerBase.cs
License : GNU General Public License v3.0
Project Creator : arunsatyarth

public List<GpuData> GetGpuList()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
                List<GpuData> gpus = new List<GpuData>();

                string graphicsCard = string.Empty;
                foreach (ManagementObject mo in searcher.Get())
                {
                    string name = mo["Name"] as string;
                    if (!string.IsNullOrEmpty(name))
                    {
                        GpuData data = new GpuData(name);
                        data.IdentifyMake();
                        gpus.Add(data);
                    }
                }
                return gpus;
            }
            catch (Exception e)
            {
            }
            return null;
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : Assistant

public static string GetOculusDir()
        {
            string OculusInstall = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)?.OpenSubKey("SOFTWARE")?.OpenSubKey("Wow6432Node")?.OpenSubKey("Oculus VR, LLC")?.OpenSubKey("Oculus")?.OpenSubKey("Config")?.GetValue("InitialAppLibrary").ToString();
            if (string.IsNullOrEmpty(OculusInstall)) return null;

            if (!string.IsNullOrEmpty(OculusInstall))
            {
                if (File.Exists(Path.Combine(OculusInstall, "Software", "hyperbolic-magnetism-beat-saber", "Beat Saber.exe")))
                {
                    return SetDir(Path.Combine(OculusInstall, "Software", "hyperbolic-magnetism-beat-saber"), "Oculus");
                }
            }

            // Yoinked this code from Umbranox's Mod Manager. Lot's of thanks and love for Umbra <3
            using (RegistryKey librariesKey = Registry.CurrentUser.OpenSubKey("Software")?.OpenSubKey("Oculus VR, LLC")?.OpenSubKey("Oculus")?.OpenSubKey("Libraries"))
            {
                // Oculus libraries uses GUID volume paths like this "\\?\Volume{0fea75bf-8ad6-457c-9c24-cbe2396f1096}\Games\Oculus Apps", we need to transform these to "D:\Game"\Oculus Apps"
                WqlObjectQuery wqlQuery = new WqlObjectQuery("SELECT * FROM Win32_Volume");
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(wqlQuery))
                {
                    Dictionary<string, string> guidLetterVolumes = new Dictionary<string, string>();

                    foreach (ManagementBaseObject disk in searcher.Get())
                    {
                        var diskId = ((string)disk.GetPropertyValue("DeviceID")).Substring(11, 36);
                        var diskLetter = ((string)disk.GetPropertyValue("DriveLetter")) + @"\";

                        if (!string.IsNullOrWhiteSpace(diskLetter))
                        {
                            guidLetterVolumes.Add(diskId, diskLetter);
                        }
                    }

                    // Search among the library folders
                    foreach (string libraryKeyName in librariesKey.GetSubKeyNames())
                    {
                        using (RegistryKey libraryKey = librariesKey.OpenSubKey(libraryKeyName))
                        {
                            string libraryPath = (string)libraryKey.GetValue("Path");
                            // Yoinked this code from Megalon's fix. <3
                            string GUIDLetter = guidLetterVolumes.FirstOrDefault(x => libraryPath.Contains(x.Key)).Value;
                            if (!string.IsNullOrEmpty(GUIDLetter))
                            {
                                string finalPath = Path.Combine(GUIDLetter, libraryPath.Substring(49), @"Software\hyperbolic-magnetism-beat-saber");
                                if (File.Exists(Path.Combine(finalPath, "Beat Saber.exe")))
                                {
                                    return SetDir(finalPath, "Oculus");
                                }
                            }
                        }
                    }
                }
            }

            return null;
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetBIOSSerialNumber()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_BIOS");
                string sBIOSSerialNumber = "";
                foreach (ManagementObject mo in searcher.Get())
                {
                    sBIOSSerialNumber = mo["SerialNumber"].ToString().Trim();
                }
                return sBIOSSerialNumber;
            }
            catch
            {
                return "";
            }
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetCPUSerialNumber()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Processor");
                string sCPUSerialNumber = "";
                foreach (ManagementObject mo in searcher.Get())
                {
                    sCPUSerialNumber = mo["ProcessorId"].ToString().Trim();
                }
                return sCPUSerialNumber;
            }
            catch
            {
                return "";
            }
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetHardDiskSerialNumber()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                string sHardDiskSerialNumber = "";
                foreach (ManagementObject mo in searcher.Get())
                {
                    sHardDiskSerialNumber = mo["SerialNumber"].ToString().Trim();
                    break;
                }
                return sHardDiskSerialNumber;
            }
            catch
            {
                return "";
            }
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetNetCardMACAddress()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))");
                string NetCardMACAddress = "";
                foreach (ManagementObject mo in searcher.Get())
                {
                    NetCardMACAddress = mo["MACAddress"].ToString().Trim();
                }
                return NetCardMACAddress;
            }
            catch
            {
                return "";
            }

        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetVideoPNPID()
        {
            string st = "";
            ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_VideoController");
            foreach (ManagementObject mo in mos.Get())
            {
                st = mo["PNPDeviceID"].ToString();
            }
            return st;
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetSoundPNPID()
        {
            string st = "";
            ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_SoundDevice");
            foreach (ManagementObject mo in mos.Get())
            {
                st = mo["PNPDeviceID"].ToString();
            }
            return st;
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetCPUVersion()
        {
            string st = "";
            ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (ManagementObject mo in mos.Get())
            {
                st = mo["Version"].ToString();
            }
            return st;
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetCPUName()
        {
            string st = "";
            ManagementObjectSearcher driveID = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (ManagementObject mo in driveID.Get())
            {
                st = mo["Name"].ToString();
            }
            return st;
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetCPUManufacturer()
        {
            string st = "";
            ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_Processor");
            foreach (ManagementObject mo in mos.Get())
            {
                st = mo["Manufacturer"].ToString();
            }
            return st;
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetBoardManufacturer()
        {
            SelectQuery query = new SelectQuery("Select * from Win32_BaseBoard");
            ManagementObjectSearcher mos = new ManagementObjectSearcher(query);
            ManagementObjectCollection.ManagementObjectEnumerator data = mos.Get().GetEnumerator();
            data.MoveNext();
            ManagementBaseObject board = data.Current;
            return board.GetPropertyValue("Manufacturer").ToString();
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetBoardID()
        {
            string st = "";
            ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
            foreach (ManagementObject mo in mos.Get())
            {
                st = mo["SerialNumber"].ToString();
            }
            return st;
        }

19 View Source File : AyFuncManagementObject.cs
License : MIT License
Project Creator : ay2015

public string GetBoardType()
        {
            string st = "";
            ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard");
            foreach (ManagementObject mo in mos.Get())
            {
                st = mo["Product"].ToString();
            }
            return st;
        }

19 View Source File : WindowChromeBehavior.cs
License : Apache License 2.0
Project Creator : beckzhu

private static bool IsWindows10OrHigher()
        {
            var version = NtDll.RtlGetVersion();
            if (default(Version) == version)
            {
                // Snippet from Koopakiller https://dotnet-snippets.de/snippet/os-version-name-mit-wmi/4929
                using (var mos = new ManagementObjectSearcher("SELECT Caption, Version FROM Win32_OperatingSystem"))
                {
                    var attribs = mos.Get().OfType<ManagementObject>();
                    //caption = attribs.FirstOrDefault().GetPropertyValue("Caption").ToString() ?? "Unknown";
                    version = new Version((attribs.FirstOrDefault()?.GetPropertyValue("Version") ?? "0.0.0.0").ToString());
                }
            }
            return version >= new Version(10, 0);
        }

19 View Source File : WMI.cs
License : GNU General Public License v3.0
Project Creator : belowaverage-org

public static Task<ManagementObjectCollection> Query(string Query, string Host)
        {
            return Task.Run(() =>
            {
                try
                {
                    ManagementScope scope = new ManagementScope(GetBestManagementScope(Host));
                    scope.Connect();
                    ObjectQuery query = new ObjectQuery(Query);
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                    ManagementObjectCollection collection = searcher.Get();
                    searcher.Dispose();
                    return collection;
                }
                catch (Exception e)
                {
                    Logger.Exception(e, "Failed to query via WMI.");
                    return null;
                }
            });
        }

See More Examples