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
19
Source : FauxDeployCMAgent.cs
with GNU General Public License v3.0
from 1RedOne
with GNU General Public License v3.0
from 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
Source : SettingsWindow.xaml.cs
with MIT License
from 3RD-Dimension
with MIT License
from 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
Source : SerialBusManager.cs
with GNU General Public License v3.0
from a4004
with GNU General Public License v3.0
from 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
Source : DellSmbiosSmi.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from 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
Source : WmiFanSpeedReader.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from 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
Source : Local.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from 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
Source : Program.cs
with MIT License
from AhmedMinegames
with MIT License
from 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
Source : USBPacker.cs
with MIT License
from AhmedMinegames
with MIT License
from 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
Source : Main.cs
with MIT License
from AhmedMinegames
with MIT License
from 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
Source : Main.cs
with MIT License
from AhmedMinegames
with MIT License
from 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
Source : MachineInfo.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from 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
Source : MachineInfo.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from 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
Source : MachineInfo.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from 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
Source : ApplicationAccess.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from 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
Source : SystemUserAccess.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from 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
Source : MachineInfo.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from 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
Source : WindowUtils.cs
with MIT License
from AlexanderPro
with MIT License
from 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
Source : SystemUtils.cs
with MIT License
from AlexanderPro
with MIT License
from 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
Source : WindowUtils.cs
with MIT License
from AlexanderPro
with MIT License
from 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
Source : WindowsSmart.cs
with MIT License
from AlexGyver
with MIT License
from 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
Source : Volumes.cs
with MIT License
from alexis-
with MIT License
from 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
Source : Resume.cs
with MIT License
from Alkl58
with MIT License
from 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
Source : Helpers.cs
with MIT License
from Alkl58
with MIT License
from 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
Source : ProcessFilter.cs
with GNU Lesser General Public License v3.0
from Alois-xx
with GNU Lesser General Public License v3.0
from 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
Source : WmiQuery.cs
with GNU General Public License v3.0
from Alois-xx
with GNU General Public License v3.0
from 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
Source : ProcessFilter.cs
with GNU Lesser General Public License v3.0
from Alois-xx
with GNU Lesser General Public License v3.0
from 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
Source : DNSChallengeWinDnsValidator.cs
with GNU General Public License v3.0
from aloopkin
with GNU General Public License v3.0
from 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
Source : frmMain.cs
with GNU General Public License v3.0
from amakvana
with GNU General Public License v3.0
from 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
Source : SystemManagement.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from 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
Source : GetInjectedThreads.cs
with MIT License
from Apr4h
with MIT License
from 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
Source : GetInjectedThreads.cs
with MIT License
from Apr4h
with MIT License
from 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
Source : SPLHelper.cs
with GNU General Public License v3.0
from ArduinoIoTDev
with GNU General Public License v3.0
from 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
Source : SPLHelper.cs
with GNU General Public License v3.0
from ArduinoIoTDev
with GNU General Public License v3.0
from 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
Source : SPLHelper.cs
with GNU General Public License v3.0
from ArduinoIoTDev
with GNU General Public License v3.0
from 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
Source : MinerBase.cs
with GNU General Public License v3.0
from arunsatyarth
with GNU General Public License v3.0
from 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
Source : Utils.cs
with MIT License
from Assistant
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : AyFuncManagementObject.cs
with MIT License
from ay2015
with MIT License
from 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
Source : WindowChromeBehavior.cs
with Apache License 2.0
from beckzhu
with Apache License 2.0
from 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
Source : WMI.cs
with GNU General Public License v3.0
from belowaverage-org
with GNU General Public License v3.0
from 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