private string getMachineCode() { // * Copyright (C) 2012 Artem Los, All rights reserved. // * // * This code will generate a 5 digits long key, finger print, of the system // * where this method is being executed. However, that might be changed in the // * hash function "GetStableHash", by changing the amount of zeroes in // * MUST_BE_LESS_OR_EQUAL_TO to the one you want to have. Ex 1000 will return // * 3 digits long hash. // * // * Please note, that you might also adjust the order of these, but remember to // * keep them there because as it is stated at // * (http://www.codeproject.com/Articles/17973/How-To-Get-Hardware-Information-CPU-ID-MainBoard-I) // * the processorID might be the same at some machines, which will generate same // * hashes for several machines. // * // * The function will probably be implemented into SKGL Project at http://skgl.codeplex.com/ // * and Software Protector at http://softwareprotector.codeplex.com/, so I // * release this code under the same terms and conditions as stated here: // * http://skgl.codeplex.com/license // * // * Any questions, please contact me at // * * [email protected] // methods m = new methods(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Processor"); string collectedInfo = ""; // here we will put the informa foreach (ManagementObject share in searcher.Get()) { // first of all, the processorid collectedInfo += share["ProcessorId"]; } searcher.Query = new ObjectQuery("select * from Win32_BIOS"); foreach (ManagementObject share in searcher.Get()) { //then, the serial number of BIOS collectedInfo += share["SerialNumber"]; } searcher.Query = new ObjectQuery("select * from Win32_BaseBoard"); foreach (ManagementObject share in searcher.Get()) { //finally, the serial number of motherboard collectedInfo += share["SerialNumber"]; } // patch luca bernardini if (string.IsNullOrEmpty(collectedInfo) | collectedInfo == "00" | collectedInfo.Length <= 3) { collectedInfo += getHddSerialNumber(); } return m.getEightByteHash(collectedInfo, 100000).ToString(); }
public static List<COMPortInfo> GetCOMPortsInfo() { List<COMPortInfo> comPortInfoList = new List<COMPortInfo>(); ConnectionOptions options = ProcessConnection.ProcessConnectionOptions(); ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2"); ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0"); ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery); using (comPortSearcher) { string caption = null; foreach (ManagementObject obj in comPortSearcher.Get()) { if (obj != null) { object captionObj = obj["Caption"]; if (captionObj != null) { caption = captionObj.ToString(); if (caption.Contains("(COM")) { COMPortInfo comPortInfo = new COMPortInfo(); comPortInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty); comPortInfo.Description = caption; comPortInfoList.Add(comPortInfo); } } } } } return comPortInfoList; }
public void Search_DFU(System.Object sender, System.ComponentModel.DoWorkEventArgs e) { DFUConnected = false; while (!(DFUConnected == true)) { if (OhNoesShutDOWN == true) { return; } //Searching for DFU... Console.Text = " "; ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Description = 'Apple Recovery (DFU) USB Driver'"); foreach (ManagementObject queryObj in searcher.Get()) { if (OhNoesShutDOWN == true) { return; } Console.Text += (queryObj("Description")); } if (Console.Text.Contains("DFU")) { if (OhNoesShutDOWN == true) { return; } //MsgBox("In DFU!", MsgBoxStyle.Information) DFUConnected = true; } } }
public static String GetHDDSerialNo() { ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); foreach (ManagementObject moDisk in mosDisks.Get()) { return moDisk["Model"].ToString() + " (" + Math.Round(((((double)Convert.ToDouble(moDisk["Size"]) / 1024) / 1024) / 1024), 2) + " GB)"; } return " "; }
private static string GetOSFriendlyName() { string result = string.Empty; ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem"); foreach (ManagementObject os in searcher.Get()) { result = os["Caption"].ToString(); break; } return result; }
protected string GetOSVersionStr() { string ret = ""; ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT Caption,CSDVersion,BuildNumber,BuildType FROM Win32_OperatingSystem"); ManagementObjectCollection queryCollection=query.Get(); foreach (ManagementObject os in queryCollection) { ret = os["Caption"].ToString() + (os["CSDVersion"] == null ? "" : " " + os["CSDVersion"].ToString()); ret += " (Build " + os["BuildNumber"].ToString() + " - " + os["BuildType"] + ")"; } return ret; }
/// <summary> /// Changes installed SonarQube service's log on user to current logged on user /// if windows authentication is chosen. /// </summary> public static bool ChangeUserAccountOfServiceForWindowsAuthentication(Session session) { string authType = session.Property("SQLAUTHTYPE"); string setupType = session.Property("SETUPTYPE"); string currentLoggedInUser = session.Property("CURRENTLOGGEDINUSER"); bool success = true; // If authentication type is Windows, we need to change the service log on to current user. // For SQL auth, it works with System log on which is the default one. if (AuthenticationType.Windows.Equals(authType, StringComparison.InvariantCultureIgnoreCase) && SetupType.Express.Equals(setupType, StringComparison.InvariantCultureIgnoreCase)) { try { string queryString = "SELECT * FROM WIN32_SERVICE WHERE DISPLAYNAME='SonarQube'"; ObjectQuery oQuery = new ObjectQuery(queryString); ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(oQuery); ManagementObjectCollection objectCollection = objectSearcher.Get(); foreach (ManagementObject mObject in objectCollection) { string serviceName = mObject.GetPropertyValue("Name") as string; string fullServiceName = "Win32_Service.Name='" + serviceName + "'"; ManagementObject mo = new ManagementObject(fullServiceName); string username = currentLoggedInUser; string password = string.Empty; // Ask current logged on user's password if (!WindowsAuthenticationHelper.PromptForPassword(session, username, out password)) { // [TODO] Localization SendMessageBoxMessageToBA(session, "Authentication failed. Service may not run as expected."); success = false; } else { mo.InvokeMethod("Change", new object[] { null, null, null, null, null, null, username, password, null, null, null }); } } } catch (Exception e) { session.Log("[ChangeUserAccountForService] {0}", e.Message); } } return success; }
public static string GetBIOScaption() { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS"); foreach (ManagementObject wmi in searcher.Get()) { try { return wmi.GetPropertyValue("Caption").ToString(); } catch { } } return "BIOS Caption: Unknown"; }
public static string GetAccountName() { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_UserAccount"); foreach (ManagementObject wmi in searcher.Get()) { try { return wmi.GetPropertyValue("Name").ToString(); } catch { } } return "User Account Name: Unknown"; }
/// <summary> /// Query for windows drives /// </summary> /// <returns>Collection of available drives</returns> public FSDrivePresentationInfo[] getDrives() { //get drive collection ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk "); ManagementObjectCollection queryCollection = query.Get(); FSDrivePresentationInfo[] drives = new FSDrivePresentationInfo[queryCollection.Count]; int i = 0; const int Removable = 2; const int LocalDisk = 3; const int Network = 4; const int CD = 5; foreach ( ManagementObject mo in queryCollection) { drives[i] = new FSDrivePresentationInfo(); drives[i].Name = mo["Name"].ToString() + "\\"; switch (int.Parse( mo["DriveType"].ToString())) { case Removable: //removable drives drives[i].ImageIndex = 5; drives[i].SelectedIndex = 5; break; case LocalDisk: //Local drives drives[i].ImageIndex = 6; drives[i].SelectedIndex = 6; break; case CD: //CD rom drives drives[i].ImageIndex = 7; drives[i].SelectedIndex = 7; break; case Network: //Network drives drives[i].ImageIndex = 8; drives[i].SelectedIndex = 8; break; default: //defalut to folder drives[i].ImageIndex = 2; drives[i].SelectedIndex = 3; break; } // don't forget to increment the counter ++i; } return drives; }
public static string get_video() { ManagementObjectSearcher searcher= new ManagementObjectSearcher("SELECT * FROM Win32_DisplayConfiguration"); string graphicsCard = string.Empty; foreach (ManagementObject mo in searcher.Get()) { foreach (PropertyData property in mo.Properties) { if (property.Name == "Description") { return property.Value.ToString(); break; } } } return graphicsCard; }
//取第一块硬盘编号 public String GetHardDiskID() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia"); String strHardDiskID = null; foreach (ManagementObject mo in searcher.Get()) { strHardDiskID = mo["SerialNumber"].ToString().Trim(); break; } return strHardDiskID; } catch { return ""; } }
/// <summary> /// Best effort to get the right port to connect to. /// NO PROMISES /// Windows part. /// </summary> /// <returns></returns> public static string GetArduinoCOMPortWindows() { List<String> list = new List<String>(); ManagementObjectSearcher searcher2 = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity"); String ardo = String.Empty; foreach (ManagementObject mo2 in searcher2.Get()) { string name = mo2["Name"].ToString(); if (name.Contains("(COM")) { if (name.Contains("Arduino")) ardo = name; } } ardo = ardo.Substring(ardo.IndexOf("COM")); ardo = ardo.Substring(0, ardo.Length - 1); return ardo; }
static void DropThisSession(string objectQry) { SelectQuery query = new SelectQuery("select ComputerName, UserName, ResourcesOpened from win32_serversession where username ='******'"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject mo in searcher.Get()) { Console.WriteLine("Session opened by: {0} from {1} with {2} resources opened", mo.Properties["UserName"].Value, mo.Properties["ComputerName"].Value, mo.Properties["ResourcesOpened"].Value); // Optionaly - Get associated serverconnection instance foreach (ManagementBaseObject b in mo.GetRelated("Win32_ServerConnection")) { ShowServerConnectionProperties(b.ToString()); } // Delete the session, this will close all opened resources (files etc..)for this session mo.Delete(); } } }
private static void Button_Click(object sender, RoutedEventArgs e) { List<USBDeviceInfo> devices = new List<USBDeviceInfo>(); ManagementObjectCollection collection; var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"); collection = searcher.Get(); foreach (var device in collection) { devices.Add(new USBDeviceInfo( (string)device.GetPropertyValue("DeviceID"), (string)device.GetPropertyValue("PNPDeviceID"), (string)device.GetPropertyValue("Description") )); } collection.Dispose(); // await _programmator.SendRandomMessage(); }
public static void WriteClientToDB(String PloobsVersion) { MySqlConnection myConnection = null; try { myConnection = new MySqlConnection(connectionstring); myConnection.Open(); String processor = System.Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER"); System.OperatingSystem osInfo = System.Environment.OSVersion; var hostEntry = Dns.GetHostEntry(Dns.GetHostName()); var ip = (from addr in hostEntry.AddressList where addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork select addr.ToString()).FirstOrDefault(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DisplayConfiguration"); string graphicsCard = string.Empty; foreach (ManagementObject mo in searcher.Get()) { foreach (PropertyData property in mo.Properties) { if (property.Name == "Description") { graphicsCard = property.Value.ToString(); } } } String mySelectQuery = "INSERT INTO UsersInfo (Name, Os, Ip, Processors,Date,VideoCard,Version) VALUES (\"" + Environment.MachineName + "\",\"" + osInfo.VersionString + "\", \"" + ip + "\", \"" + processor + "\",\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\" , \"" + graphicsCard + "\", \"" + PloobsVersion + "\")"; MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection); myCommand.ExecuteNonQuery(); } catch (Exception ex) { ///nothing =P } finally { myConnection.Close(); } }
/// <summary> /// Gets a list of the current installed memory banks on the machine. /// </summary> public static List <RamInfo> GetMemory() { List <RamInfo> memoryModules = null; ManagementObjectSearcher memoryQuery = new ManagementObjectSearcher( @"SELECT MemoryType, Capacity, Speed FROM Win32_PhysicalMemory " ); try { ManagementObjectCollection memoryInfo = memoryQuery.Get(); memoryModules = new List <RamInfo>(); foreach (var item in memoryInfo) { RamInfo ram = new RamInfo(); ram.MemoryType = RamInfo.ObtainType((UInt32.Parse(item["MemoryType"].ToString()))); ram.Capacity = (int)(UInt64.Parse(item["Capacity"].ToString()) / 1073741824); ram.Speed = Int32.Parse(item["Speed"].ToString()); memoryModules.Add(ram); } } catch (Exception exc) { Logger.Error("GetMemory() error...", exc); memoryModules = null; } return(memoryModules); }
public static int KillProcessAndChildren(int pid) { int killed = 0; if (pid == 0) { return(killed); } ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid); ManagementObjectCollection moc = searcher.Get(); foreach (var mo in moc) { var procId = Convert.ToInt32(mo["ProcessID"]); if (procId == pid) { continue; } killed += KillProcessAndChildren(procId); } try { Process proc = Process.GetProcessById(pid); proc.Kill(); killed++; } catch (ArgumentException) { Console.WriteLine("Cannot kill process with pid= " + pid + " because it already exited"); } catch (Exception e) { Console.WriteLine("Cannot kill process with pid= " + pid + " because of exception: " + e.Message); } return(killed); }
private static IList <EBookReaderDevices> GetUsbDevices() { List <EBookReaderDevices> devices = new List <EBookReaderDevices>(); ManagementObjectCollection collection; SelectQuery selectQuery = new SelectQuery("Win32_DiskDrive"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery)) collection = searcher.Get(); foreach (ManagementObject device in collection) { EBookReaderDevices reader = new EBookReaderDevices(); reader.DeviceID = device.GetPropertyValue("DeviceID").ToString(); reader.PNPDeviceID = device.GetPropertyValue("PNPDeviceID").ToString(); reader.Description = device.GetPropertyValue("Description").ToString(); reader.Manufacturer = device.GetPropertyValue("Manufacturer").ToString(); reader.Model = device.GetPropertyValue("Model").ToString(); foreach (ManagementObject partition in device.GetRelated("Win32_DiskPartition")) { reader.Name = partition.GetPropertyValue("Name").ToString(); foreach (ManagementObject logical in partition.GetRelated("Win32_LogicalDisk")) { reader.LogicalDisk = logical.GetPropertyValue("Name").ToString(); } } if (reader.Model == Kindle) { devices.Add(reader); } } collection.Dispose(); return(devices); }
public static string GetOSVersion() { string propertyDataValueCaption = string.Empty; const string propertyDataNameCaption = "Caption"; string propertyDataValueBuildNumber = string.Empty; const string propertyDataNameBuildNumber = "BuildNumber"; var win32DeviceClassName = "Win32_OperatingSystem"; var query = string.Format("select * from {0}", win32DeviceClassName); try { using (var searcher = new ManagementObjectSearcher(query)) { ManagementObjectCollection objectCollection = searcher.Get(); foreach (ManagementBaseObject managementBaseObject in objectCollection) { foreach (PropertyData propertyData in managementBaseObject.Properties) { if (propertyData.Name == propertyDataNameCaption) { propertyDataValueCaption = (string)propertyData.Value; } if (propertyData.Name == propertyDataNameBuildNumber) { propertyDataValueBuildNumber = (string)propertyData.Value; } } } } } catch { propertyDataValueCaption = "Windows OS"; } return($"{propertyDataValueCaption} Build {propertyDataValueBuildNumber}"); }
private string?FindConnectedPort() { _logger.LogTrace("Starting search for virtual COM device with name: {name}", _deviceName); string?foundPort = null; try { using var search = new ManagementObjectSearcher( "root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\""); foreach (ManagementBaseObject mgmtObj in search.Get()) { var queryObj = mgmtObj as ManagementObject; var name = queryObj?[_mgmtObjQuery] as string; if (name is null) { return(null); } if (name.Contains(_deviceName)) { var port = Regex.Match(name, _portRegex).Groups[1].Value; foundPort = port; break; } } } catch (Exception e) { _logger.LogError(e, "Error whilst looking for virtual COM device {name}", _deviceName); } return(foundPort); }
public void BootMachine() { ConnectionOptions BootConn = new ConnectionOptions(); BootConn.Username = strAdmin; BootConn.Password = strPassword; ManagementScope ms = new ManagementScope("\\\\" + strIp + "\\root\\cimv2", BootConn); ms.Options.EnablePrivileges = true; WriteLog.WriteLogFile("", strIp + ":00"); if (!string.IsNullOrEmpty(strAdmin) && !string.IsNullOrEmpty(strPassword)) { try { ms.Connect(); } catch { } } if (ms.IsConnected) { try { WriteLog.WriteLogFile("", strIp + ":11"); ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher mos = new ManagementObjectSearcher(ms, oq); ManagementObjectCollection moc = mos.Get(); foreach (ManagementObject mo in moc) { string[] ss = inParams; mo.InvokeMethod(strMothod, ss); } } catch (Exception ex) { WriteLog.WriteLogFile("", strIp + ":" + ex.Message + "网络不通或用户名、密码不正确!"); } } WriteLog.WriteLogFile("", ms.IsConnected + ":30"); }
private void timer_Tick(object sender, EventArgs e) { float fCPU = pCPU.NextValue(); float fRAM = pRAM.NextValue(); progressBarCPU.Value = (int)fCPU; lbCPU.Text = string.Format("{0:0.00}%", fCPU); progressBarRAM.Value = (int)fRAM; lbRAM.Text = string.Format("{0:0.00}%", fRAM); chart1.Series["CPU"].Points.AddY(fCPU); chart1.Series["RAM"].Points.AddY(fRAM); int iThread = (int)pThread.NextValue(); lbThread.Text = "Số Thread :" + iThread; int iHandle = (int)pHandle.NextValue(); lbHandle.Text = "Số Handle :" + iHandle; //lbSpeed.Text = ("Speed : " + getd()); TimeSpan ts = TimeSpan.FromSeconds(pUpTime.NextValue()); lbUpTime.Text = ("Up Time: " + ts.Days + ":" + ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds); ManagementObjectSearcher ClockSpeedSearch = new ManagementObjectSearcher("select CurrentClockSpeed from Win32_Processor"); foreach (var item in ClockSpeedSearch.Get()) { var clockSpeed = (uint)item["CurrentClockSpeed"]; lbSpeed.Invoke((MethodInvoker)(() => lbSpeed.Text = "CPU Clock Speed: " + clockSpeed + "Mhz")); } }
/// <summary>获取WMI信息</summary> /// <param name="path"></param> /// <param name="property"></param> /// <returns></returns> public static String GetInfo(String path, String property) { // Linux Mono不支持WMI if (Runtime.Mono) { return(""); } var bbs = new List <String>(); try { var wql = String.Format("Select {0} From {1}", property, path); var cimobject = new ManagementObjectSearcher(wql); var moc = cimobject.Get(); foreach (var mo in moc) { if (mo != null && mo.Properties != null && mo.Properties[property] != null && mo.Properties[property].Value != null) { bbs.Add(mo.Properties[property].Value.ToString()); } } } catch (Exception ex) { //XTrace.WriteException(ex); XTrace.WriteLine("WMI.GetInfo({0})失败!{1}", path, ex.Message); return(""); } bbs.Sort(); return(bbs.Distinct().Join()); }
/// <summary> /// 杀死进程和他的子进程 /// Code from https://stackoverflow.com/questions/30249873/process-kill-doesnt-seem-to-kill-the-process /// </summary> /// <param name="pid"></param> public static void KillProcessAndChildrens(int pid) { #if !LINUX ManagementObjectSearcher processSearcher = new ManagementObjectSearcher ("Select * From Win32_Process Where ParentProcessID=" + pid); ManagementObjectCollection processCollection = processSearcher.Get(); try { Process proc = Process.GetProcessById(pid); if (!proc.HasExited) { proc.Kill(); } } catch (ArgumentException) { // Process already exited. } catch (Win32Exception e) { SLogger.Warn("Unknow exception", e); } if (processCollection != null) { foreach (ManagementObject mo in processCollection) { KillProcessAndChildrens(Convert.ToInt32(mo["ProcessID"])); //kill child processes(also kills childrens of childrens etc.) } } #else if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new NotImplementedException(); } #endif }
private static ManagementObject get80211InterfaceByMac(String macAddress) { ManagementObject instance = null; /*using (ManagementObjectSearcher mos = new ManagementObjectSearcher(@"SELECT * * FROM Win32_NetworkAdapter * WHERE Manufacturer != 'Microsoft' * AND NOT PNPDeviceID LIKE 'ROOT\\%' * AND NetConnectionID LIKE 'Wireless%' * AND MACAddress LIKE'" + macAddress + "'")) * {*/ using (ManagementObjectSearcher mos = new ManagementObjectSearcher(@"SELECT * FROM Win32_NetworkAdapter WHERE Manufacturer != 'Microsoft' AND NOT PNPDeviceID LIKE 'ROOT\\%' AND (NetConnectionID LIKE 'Wireless%' OR NetConnectionID LIKE 'WiFi%')" + //Needed for Windows 8 "AND MACAddress LIKE'" + macAddress + "'")) { IEnumerable <ManagementObject> mOs80211 = mos.Get().Cast <ManagementObject>(); foreach (ManagementObject mo in mOs80211) { instance = mo; } if (instance != null) { Console.WriteLine("Interface found."); } else { Console.WriteLine("Interface not found."); } return(instance); } }
//////////////////////////////////////////////////////////////////////////////////////////////////// private ArduinoProperties AutoDetectArduinoPort() { ManagementScope connectionScope = new ManagementScope(); SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery); ArduinoProperties result = new ArduinoProperties(); try { foreach (ManagementObject item in searcher.Get()) { string desc = item["Description"].ToString(); string deviceId = item["DeviceID"].ToString(); string pnp = item["PNPDeviceID"].ToString(); if (desc.Contains("Arduino") || pnp.Contains("VID_10C4") ||// Vietduino pnp.Contains("VID_2341")) //arduino) { result.portName = deviceId; } var config = item.GetRelated("Win32_SerialPortConfiguration").Cast <ManagementObject>().ToList().FirstOrDefault(); result.baudRate = (config != null) ? int.Parse(config["BaudRate"].ToString()) : int.Parse(item["MaxBaudRate"].ToString()); } } catch (ManagementException e) { throw new Exception("Can not get Arduino port, please check connection"); } return(result); }
/// <summary> /// Gets a list of the current processors installed on the machine. /// </summary> public static List <CpuInfo> GetProcessors() { List <CpuInfo> processors = null; ManagementObjectSearcher processorQuery = new ManagementObjectSearcher( @"SELECT Name, NumberOfLogicalProcessors, MaxClockSpeed FROM Win32_Processor" ); try { ManagementObjectCollection processorInfo = processorQuery.Get(); processors = new List <CpuInfo>(); foreach (ManagementObject item in processorInfo) { CpuInfo cpu = new CpuInfo(); cpu.Name = item["Name"].ToString(); cpu.Threads = Int32.Parse(item["NumberOfLogicalProcessors"].ToString()); cpu.MaxClockSpeed = Int32.Parse(item["MaxClockSpeed"].ToString()); processors.Add(cpu); } } catch (Exception exc) { Logger.Error("GetProcessors() error...", exc); processors = null; } return(processors); }
static string ToMofString(ManagementClass wmiClass) { var mofString = string.Empty; // print the (qualified) class name, and then all of the (qualified) properties mofString += ToMofString(wmiClass.Qualifiers, string.Empty, "\n"); mofString += $"class {wmiClass["__CLASS"]} : {wmiClass["__SUPERCLASS"]}\n"; mofString += "{\n"; var orderedProperties = new SortedDictionary<int, string>(); foreach (PropertyData pd in wmiClass.Properties) { if (!pd.IsLocal) continue; // sort properties according to the WmiDataId qualifer (if available) var propertyString = $"\t{ToMofString(pd.Qualifiers, "\t", " ")}{pd.Type.ToString().ToLower()} {pd.Name};\n"; var propertyMatch = new Regex(@"wmidataid\((?<WmiDataId>\d+)\)", RegexOptions.IgnoreCase).Match(propertyString); if (propertyMatch.Success) orderedProperties[Convert.ToInt32(propertyMatch.Groups["WmiDataId"].Value)] = propertyString; else mofString += propertyString; } foreach (var propertyString in orderedProperties.Values) { mofString += propertyString; } mofString += "};\n\n"; // event details are in descendant classes of the top-level (EventTrace) provider class // so also enumerate all of the children on this class var providerSearcher = new ManagementObjectSearcher("root\\WMI", $"SELECT * FROM meta_class WHERE __superclass = '{wmiClass["__CLASS"]}'", null); foreach (ManagementClass providerClass in providerSearcher.Get()) { mofString += ToMofString(providerClass); } return mofString; }
public static IEnumerable <BaseService> Retrieve(ManagementScope managementScope) { var objectQuery = new ObjectQuery("SELECT * FROM Win32_BaseService"); var objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery); var objectCollection = objectSearcher.Get(); foreach (ManagementObject managementObject in objectCollection) { yield return new BaseService { AcceptPause = (bool)(managementObject.Properties["AcceptPause"]?.Value ?? default(bool)), AcceptStop = (bool)(managementObject.Properties["AcceptStop"]?.Value ?? default(bool)), Caption = (string)(managementObject.Properties["Caption"]?.Value), CreationClassName = (string)(managementObject.Properties["CreationClassName"]?.Value), Description = (string)(managementObject.Properties["Description"]?.Value), DesktopInteract = (bool)(managementObject.Properties["DesktopInteract"]?.Value ?? default(bool)), DisplayName = (string)(managementObject.Properties["DisplayName"]?.Value), ErrorControl = (string)(managementObject.Properties["ErrorControl"]?.Value), ExitCode = (uint)(managementObject.Properties["ExitCode"]?.Value ?? default(uint)), InstallDate = ManagementDateTimeConverter.ToDateTime(managementObject.Properties["InstallDate"]?.Value as string ?? "00010102000000.000000+060"), Name = (string)(managementObject.Properties["Name"]?.Value), PathName = (string)(managementObject.Properties["PathName"]?.Value), ServiceSpecificExitCode = (uint)(managementObject.Properties["ServiceSpecificExitCode"]?.Value ?? default(uint)), ServiceType = (string)(managementObject.Properties["ServiceType"]?.Value), Started = (bool)(managementObject.Properties["Started"]?.Value ?? default(bool)), StartMode = (string)(managementObject.Properties["StartMode"]?.Value), StartName = (string)(managementObject.Properties["StartName"]?.Value), State = (string)(managementObject.Properties["State"]?.Value), Status = (string)(managementObject.Properties["Status"]?.Value), SystemCreationClassName = (string)(managementObject.Properties["SystemCreationClassName"]?.Value), SystemName = (string)(managementObject.Properties["SystemName"]?.Value), TagId = (uint)(managementObject.Properties["TagId"]?.Value ?? default(uint)) } } ; } }
public void Read_Event_From_Log_With_WMI() { //Arrange Debug.WriteLine("Testing Wmi Method Write_And_Read_Event_From_Log_With_WMI(), yeah."); DateTime FromTime = DateTime.Now.AddDays(-1); // string SomeDateTime = "20130526000000.000000+000"; string strFromTime = String.Format(Global_Const.DATE_FORMAT_STR, FromTime) + ".000000+000"; string wmiQuery = String.Format("SELECT * FROM Win32_NTLogEvent WHERE Logfile = '{0}' AND TimeGenerated > '{1}'", Global_Const.SOURCE, strFromTime); //Act var mos = new ManagementObjectSearcher(wmiQuery); // mos. //EventLogEntryCollection eventLogEntryCollection = (EventLogEntryCollection)mos.Container; object o; Debug.WriteLine("***** Start writing Properties *****"); List <EventRecord> EventRecordList = new List <EventRecord>(); foreach (ManagementObject mo in mos.Get()) { EventRecordList.Add(new EventRecord(mo)); Debug.WriteLine("***** New Managment Object from Eventstore *****"); Debug.WriteLine(String.Format("{0}: {1}", "Message", EventRecordList[EventRecordList.Count - 1].Message)); // EventLogEntry eventLogRow = (EventLogEntry)mo; //foreach (PropertyData pd in mo.Properties) //{ // o = mo[pd.Name]; // if (o != null) // { // Debug.WriteLine(String.Format("{0}: {1}", pd.Name, mo[pd.Name].ToString())); // } //} } //Assert Assert.IsTrue(EventRecordList.Count > 0, "There should be some events last day"); }
public static IEnumerable <AlarmDevice> Retrieve(ManagementScope managementScope) { var objectQuery = new ObjectQuery("SELECT * FROM CIM_AlarmDevice"); var objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery); var objectCollection = objectSearcher.Get(); foreach (ManagementObject managementObject in objectCollection) { yield return new AlarmDevice { AudibleAlarm = (bool)(managementObject.Properties["AudibleAlarm"]?.Value ?? default(bool)), Availability = (ushort)(managementObject.Properties["Availability"]?.Value ?? default(ushort)), Caption = (string)(managementObject.Properties["Caption"]?.Value), ConfigManagerErrorCode = (uint)(managementObject.Properties["ConfigManagerErrorCode"]?.Value ?? default(uint)), ConfigManagerUserConfig = (bool)(managementObject.Properties["ConfigManagerUserConfig"]?.Value ?? default(bool)), CreationClassName = (string)(managementObject.Properties["CreationClassName"]?.Value), Description = (string)(managementObject.Properties["Description"]?.Value), DeviceId = (string)(managementObject.Properties["DeviceID"]?.Value), ErrorCleared = (bool)(managementObject.Properties["ErrorCleared"]?.Value ?? default(bool)), ErrorDescription = (string)(managementObject.Properties["ErrorDescription"]?.Value), InstallDate = ManagementDateTimeConverter.ToDateTime(managementObject.Properties["InstallDate"]?.Value as string ?? "00010102000000.000000+060"), LastErrorCode = (uint)(managementObject.Properties["LastErrorCode"]?.Value ?? default(uint)), Name = (string)(managementObject.Properties["Name"]?.Value), PnpDeviceId = (string)(managementObject.Properties["PNPDeviceID"]?.Value), PowerManagementCapabilities = (ushort[])(managementObject.Properties["PowerManagementCapabilities"]?.Value ?? new ushort[0]), PowerManagementSupported = (bool)(managementObject.Properties["PowerManagementSupported"]?.Value ?? default(bool)), Status = (string)(managementObject.Properties["Status"]?.Value), StatusInfo = (ushort)(managementObject.Properties["StatusInfo"]?.Value ?? default(ushort)), SystemCreationClassName = (string)(managementObject.Properties["SystemCreationClassName"]?.Value), SystemName = (string)(managementObject.Properties["SystemName"]?.Value), Urgency = (ushort)(managementObject.Properties["Urgency"]?.Value ?? default(ushort)), VisibleAlarm = (bool)(managementObject.Properties["VisibleAlarm"]?.Value ?? default(bool)) } } ; } }
private void GetWin32OperatingSystemData() { ManagementObjectSearcher searcher = new ManagementObjectSearcher(QueryOperatingSystem); ManagementObjectCollection objCol = searcher.Get(); try { foreach (var o in objCol) { var mgtObject = (ManagementObject)o; var productType = int.Parse(mgtObject["ProductType"].ToString()); switch (productType) { case 1: _productType = Workstation; break; case 2: _productType = DomainController; break; case 3: _productType = Server; break; default: _productType = Unknown + $" [{productType}]"; break; } } } catch { // Do Nothing } }
// Returns an Expando object with the description and username of a process from the process ID. public ExpandoObject GetProcessExtraInformation(int processId) { string query = "Select * From Win32_Process Where ProcessID = " + processId; ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementObjectCollection processList = searcher.Get(); // Create a dynamic object to store some properties on it dynamic response = new ExpandoObject(); response.Description = ""; response.Username = "******"; foreach (ManagementObject obj in processList) { // Retrieve username string[] argList = new string[] { string.Empty, string.Empty }; int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); if (returnVal == 0) { // return Username response.Username = argList[0]; } // Retrieve process description if exists if (obj["ExecutablePath"] != null) { try { FileVersionInfo info = FileVersionInfo.GetVersionInfo(obj["ExecutablePath"].ToString()); response.Description = info.FileDescription; } catch { } } } return(response); }
public static IEnumerable <Win32PrinterDriver> Retrieve(ManagementScope managementScope) { var objectQuery = new ObjectQuery("SELECT * FROM Win32_PrinterDriver"); var objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery); var objectCollection = objectSearcher.Get(); foreach (ManagementObject managementObject in objectCollection) { yield return new Win32PrinterDriver { Caption = (string)(managementObject.Properties["Caption"]?.Value), ConfigFile = (string)(managementObject.Properties["ConfigFile"]?.Value), CreationClassName = (string)(managementObject.Properties["CreationClassName"]?.Value), DataFile = (string)(managementObject.Properties["DataFile"]?.Value), DefaultDataType = (string)(managementObject.Properties["DefaultDataType"]?.Value), DependentFiles = (string[])(managementObject.Properties["DependentFiles"]?.Value ?? new string[0]), Description = (string)(managementObject.Properties["Description"]?.Value), DriverPath = (string)(managementObject.Properties["DriverPath"]?.Value), FilePath = (string)(managementObject.Properties["FilePath"]?.Value), HelpFile = (string)(managementObject.Properties["HelpFile"]?.Value), InfName = (string)(managementObject.Properties["InfName"]?.Value), InstallDate = ManagementDateTimeConverter.ToDateTime(managementObject.Properties["InstallDate"]?.Value as string ?? "00010102000000.000000+060"), MonitorName = (string)(managementObject.Properties["MonitorName"]?.Value), Name = (string)(managementObject.Properties["Name"]?.Value), OemUrl = (string)(managementObject.Properties["OEMUrl"]?.Value), Started = (bool)(managementObject.Properties["Started"]?.Value ?? default(bool)), StartMode = (string)(managementObject.Properties["StartMode"]?.Value), Status = (string)(managementObject.Properties["Status"]?.Value), SupportedPlatform = (string)(managementObject.Properties["SupportedPlatform"]?.Value), SystemCreationClassName = (string)(managementObject.Properties["SystemCreationClassName"]?.Value), SystemName = (string)(managementObject.Properties["SystemName"]?.Value), Version = (ushort)(managementObject.Properties["Version"]?.Value ?? default(ushort)) } } ; } }
private async Task KillProcessChildren(UInt32 parentProcessId) { ManagementObjectSearcher searcher = new ManagementObjectSearcher( "SELECT * " + "FROM Win32_Process " + "WHERE ParentProcessId=" + parentProcessId); ManagementObjectCollection collection = searcher.Get(); if (collection.Count > 0) { Program.LogInfo("Killing [" + collection.Count + "] processes spawned by process with Id [" + parentProcessId + "]"); foreach (var item in collection) { UInt32 childProcessId = (UInt32)item["ProcessId"]; if (childProcessId != Process.GetCurrentProcess().Id) { await KillProcessChildren(childProcessId); try { var childProcess = Process.GetProcessById((int)childProcessId); Program.LogInfo("Killing child process [" + childProcess.ProcessName + "] with Id [" + childProcessId + "]"); childProcess.Kill(); } catch (ArgumentException) { Program.LogInfo("Child process already terminated"); } catch (Win32Exception) { Program.LogInfo("Cannot kill windows child process."); } } } } }
public static IList <Disk> get_disk() { var disks = new List <Disk>(); var scope = new ManagementScope(Functions.GetServerName()); var query = new SelectQuery("Select FreeSpace,Size,Name,VolumeName from Win32_LogicalDisk where DriveType=3"); var searcher = new ManagementObjectSearcher(scope, query); foreach (var x in searcher.Get()) { var availableValue = x["FreeSpace"]; var totalSizeValue = x["Size"]; var total = totalSizeValue == null ? 0 : (ulong)totalSizeValue; var free = availableValue == null ? 0 : (ulong)availableValue; var used = total - free; var percentUsed = 0; if (total > 0) { percentUsed = (int)(((float)used / (float)total) * 100); } var disk = new Disk( name: x["Name"].ToString(), volume: x["VolumeName"].ToString(), total: total, used: used, free: free, perUsed: percentUsed ); disks.Add(disk); } return(disks); }
// method to show all services public void ListAllServices() { // create scope listServicesScope ManagementScope listServicesScope = new ManagementScope("\\\\.\\ROOT\\cimv2"); //create Query listServicesQuery that selects all from win32_services ObjectQuery listServicesQuery = new ObjectQuery("SELECT * FROM Win32_Service"); // create windowsServiceSearcher that uses listServicesScope and listServicesQuery as parameter ManagementObjectSearcher windowsServicesSearcher = new ManagementObjectSearcher(listServicesScope, listServicesQuery); // create windowsServiceCollector that stores the objects that the windowsServicesSearcher has found ManagementObjectCollection windowsServiceCollector = windowsServicesSearcher.Get(); // prints out how many services that are stored in the windowsServiceCollector Console.WriteLine("There are {0} Windows services: ", windowsServiceCollector.Count); // this line sets the Bufferheight of console to 32766 = its maximum value. so that i can print out all information // on console without it cutting the first lines that it prints out. Console.BufferHeight = 32766; // enumerate through windowsServiceColletor foreach (ManagementObject windowsService in windowsServiceCollector) { // takes the properties of windowsService and stores it in serviceProperties dataCollection PropertyDataCollection serviceProperties = windowsService.Properties; // enumerate through serviceProperties foreach (PropertyData serviceProperty in serviceProperties) { // checks if theres still properties left in the serviceProperty dataCollection if (serviceProperty.Value != null) { // print out the properties Console.WriteLine("Windows service property name: {0}", serviceProperty.Name); Console.WriteLine("Windows service property value: {0}", serviceProperty.Value); } } Console.WriteLine("---------------------------------------"); } }
private void LoadClasses() { try { string machineName = ApplyConfigVarsOnField(txtMachine.Text); if (cboNamespace.Text != null && cboNamespace.Text.Length > 0) { string strScope = string.Format(@"\\{0}\" + cboNamespace.Text, machineName); ManagementObjectSearcher searcher = new ManagementObjectSearcher( new ManagementScope( strScope), new WqlObjectQuery( "select * from meta_class"), null); cboClass.Items.Clear(); foreach (ManagementClass wmiClass in searcher.Get()) { foreach (QualifierData qd in wmiClass.Qualifiers) { // If the class is dynamic, add it to the list. if (qd.Name.Equals("dynamic") || qd.Name.Equals("static")) { cboClass.Items.Add( wmiClass["__CLASS"].ToString()); } } } LoadProperties(); CheckOKEnabled(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void funcPopulateAccounts() { AccountTimer = Stopwatch.StartNew(); SelectQuery QueryACs = new SelectQuery("SELECT * FROM Win32_Account"); ManagementObjectCollection moc = new ManagementObjectSearcher(QueryACs).Get(); Parallel.ForEach(moc.Cast <ManagementObject>(), mo => { Account Account = new Account(mo); switch (Account.AccountType) { case "User": UserAccounts.Add(Account); break; case "Group": GroupAccounts.Add(Account); break; case "Domain": DomainAccounts.Add(Account); break; case "Alias": AliasAccounts.Add(Account); break; case "WellKnownGroup": WKGAccounts.Add(Account); break; case "DeletedAccount": DeletedAccounts.Add(Account); break; case "Invalid": InvalidAccounts.Add(Account); break; case "Unknown": UnknownAccounts.Add(Account); break; case "Computer": ComputerAccounts.Add(Account); break; default: break; } }); AccountTimer.Stop(); AccountElapsedTime = AccountTimer.ElapsedMilliseconds; }
public static IEnumerable <PhysicalPackage> Retrieve(ManagementScope managementScope) { var objectQuery = new ObjectQuery("SELECT * FROM CIM_PhysicalPackage"); var objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery); var objectCollection = objectSearcher.Get(); foreach (ManagementObject managementObject in objectCollection) { yield return new PhysicalPackage { Caption = (string)(managementObject.Properties["Caption"]?.Value), CreationClassName = (string)(managementObject.Properties["CreationClassName"]?.Value), Depth = (float)(managementObject.Properties["Depth"]?.Value ?? default(float)), Description = (string)(managementObject.Properties["Description"]?.Value), Height = (float)(managementObject.Properties["Height"]?.Value ?? default(float)), HotSwappable = (bool)(managementObject.Properties["HotSwappable"]?.Value ?? default(bool)), InstallDate = ManagementDateTimeConverter.ToDateTime(managementObject.Properties["InstallDate"]?.Value as string ?? "00010102000000.000000+060"), Manufacturer = (string)(managementObject.Properties["Manufacturer"]?.Value), Model = (string)(managementObject.Properties["Model"]?.Value), Name = (string)(managementObject.Properties["Name"]?.Value), OtherIdentifyingInfo = (string)(managementObject.Properties["OtherIdentifyingInfo"]?.Value), PartNumber = (string)(managementObject.Properties["PartNumber"]?.Value), PoweredOn = (bool)(managementObject.Properties["PoweredOn"]?.Value ?? default(bool)), Removable = (bool)(managementObject.Properties["Removable"]?.Value ?? default(bool)), Replaceable = (bool)(managementObject.Properties["Replaceable"]?.Value ?? default(bool)), SerialNumber = (string)(managementObject.Properties["SerialNumber"]?.Value), Sku = (string)(managementObject.Properties["SKU"]?.Value), Status = (string)(managementObject.Properties["Status"]?.Value), Tag = (string)(managementObject.Properties["Tag"]?.Value), Version = (string)(managementObject.Properties["Version"]?.Value), Weight = (float)(managementObject.Properties["Weight"]?.Value ?? default(float)), Width = (float)(managementObject.Properties["Width"]?.Value ?? default(float)) } } ; } }
/// <summary> /// 유선 or 무선 IPv4 Address 구하기 /// </summary> /// <param name="wired">유선을 찾고 싶으면 true</param> /// <returns>IPv4 Address 문자열 배열</returns> private static string[] GetIPv4Address(bool wired) { // IPv4 검사할 정규식 Regex regex = new Regex(@"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$"); List <string> ipv4s = new List <string>(); string[] wifiNames = GetWifiNetAdapterNames(); try { ManagementObjectSearcher objSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'"); ManagementObjectCollection objCollection = objSearcher.Get(); foreach (ManagementObject obj in objCollection) { // wired값에 따라 무선 or 유선인것만 찾기 if (wired && Array.IndexOf(wifiNames, (string)obj["Description"]) < 0 || !wired && Array.IndexOf(wifiNames, (string)obj["Description"]) > -1) { foreach (string address in (string[])obj["IPAddress"]) { if (regex.IsMatch(address) && address != "0.0.0.0") { ipv4s.Add(address); } } } } } catch (Exception ex) { Console.WriteLine("Error : " + ex.ToString()); } // 반환 return(ipv4s.ToArray()); }
// privesc checks public static void GetModifiableServiceBinaries() { try { // finds any service binaries that the current can modify // TODO: or modify the parent folder ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\cimv2", "SELECT * FROM win32_service"); ManagementObjectCollection data = wmiData.Get(); Console.WriteLine("\r\n\r\n=== Modifiable Service Binaries ===\r\n"); foreach (ManagementObject result in data) { if (result["PathName"] != null) { Match path = Regex.Match(result["PathName"].ToString(), @"^\W*([a-z]:\\.+?(\.exe|\.dll|\.sys))\W*", RegexOptions.IgnoreCase); String binaryPath = path.Groups[1].ToString(); if (CheckModifiableAccess(binaryPath)) { Console.WriteLine(" Name : {0}", result["Name"]); Console.WriteLine(" DisplayName : {0}", result["DisplayName"]); Console.WriteLine(" Description : {0}", result["Description"]); Console.WriteLine(" State : {0}", result["State"]); Console.WriteLine(" StartMode : {0}", result["StartMode"]); Console.WriteLine(" PathName : {0}", result["PathName"]); Console.WriteLine(); } } } } catch (Exception ex) { Console.WriteLine(String.Format(" [X] Exception: {0}", ex.Message)); } }
public static IEnumerable <CcmLogicalMemoryConfiguration> Retrieve(ManagementScope managementScope) { var objectQuery = new ObjectQuery("SELECT * FROM CCM_LogicalMemoryConfiguration"); var objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery); var objectCollection = objectSearcher.Get(); foreach (ManagementObject managementObject in objectCollection) { yield return new CcmLogicalMemoryConfiguration { AvailableVirtualMemory = (ulong)(managementObject.Properties["AvailableVirtualMemory"]?.Value ?? default(ulong)), Name = (string)managementObject.Properties["Name"]?.Value, TotalPageFileSpace = (ulong)(managementObject.Properties["TotalPageFileSpace"]?.Value ?? default(ulong)), TotalPhysicalMemory = (ulong)(managementObject.Properties["TotalPhysicalMemory"]?.Value ?? default(ulong)), TotalVirtualMemory = (ulong)(managementObject.Properties["TotalVirtualMemory"]?.Value ?? default(ulong)) } } ; } }
public static string GetServiceTag() { string serviceTag = null; try //Use WMI for finding BIOS information { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS"); foreach (ManagementObject queryObj in searcher.Get()) { serviceTag = queryObj["SerialNumber"].ToString(); } } catch (ManagementException e) { Console.ForegroundColor = ConsoleColor.Red; LogActionToFile($"An error occurred while querying for WMI data: {e.Message}"); Console.WriteLine($"An error occurred while querying for WMI data: {e.Message}"); Console.ReadKey(); Environment.Exit(0); } return(serviceTag); }
public List <Monitor> GetMonitorList() { List <Monitor> monitorList = new List <Monitor>(); using ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor WHERE PNPDeviceID IS NOT NULL"); foreach (ManagementObject mo in mos.Get()) { Monitor monitor = new Monitor { Caption = GetPropertyString(mo["Caption"]), Description = GetPropertyString(mo["Description"]), MonitorManufacturer = GetPropertyString(mo["MonitorManufacturer"]), MonitorType = GetPropertyString(mo["MonitorType"]), Name = GetPropertyString(mo["Name"]), PixelsPerXLogicalInch = GetPropertyValue <uint>(mo["PixelsPerXLogicalInch"]), PixelsPerYLogicalInch = GetPropertyValue <uint>(mo["PixelsPerYLogicalInch"]) }; monitorList.Add(monitor); } return(monitorList); }
public static string getmac() { if (mac_ == null) { int ver = Environment.OSVersion.Version.Major; string str = "Select MACAddress,PNPDeviceID,NetConnectionStatus,Availability,NetEnabled FROM Win32_NetworkAdapter WHERE MACAddress IS NOT NULL AND PNPDeviceID IS NOT NULL"; if (ver < 6) str = "Select MACAddress,PNPDeviceID,Availability FROM Win32_NetworkAdapter WHERE MACAddress IS NOT NULL AND PNPDeviceID IS NOT NULL"; ManagementObjectSearcher searcher = new ManagementObjectSearcher(str); ManagementObjectCollection mObject = searcher.Get(); mac_ = "000000000000"; foreach (ManagementObject obj in mObject) { string pnp = obj["PNPDeviceID"].ToString(); UInt16 ss = (UInt16)(obj["Availability"]); Boolean enabled = true; UInt16 status = 2; if (ver >= 6) { try { enabled = (Boolean)(obj["NetEnabled"]); } catch { } try { status = (UInt16)(obj["NetConnectionStatus"]); } catch { } } int a = status; if (pnp.Contains("PCI\\") && status == 2 && ss == 3 && enabled) { string mac = obj["MACAddress"].ToString(); mac = mac.Replace(":", string.Empty); mac_ = mac.ToLower(); break; } } } return mac_; }
/// <summary> /// 主板编号 /// </summary> /// <returns></returns> public string GetGroupName() { string result = ""; ManagementObjectSearcher searcher = new ManagementObjectSearcher("rootCIMV2", "SELECT * FROM Win32_Group"); ManagementObjectCollection moCollection = searcher.Get(); foreach (ManagementObject mObject in moCollection) { result += mObject["Name"].ToString() + " "; } return result; }
/// <summary> /// Création des compteurs disque /// </summary> private void CreateDisk() { foreach (SimpleCounter counter in WindowsMonitorLib.Counters.CounterFactory.CreatePhysicalDiskCounters()) { AddCounterControl(counter, Color.MediumOrchid, "userControlCounterDisk", string.Format("Disk activity {0}", counter.Name)); } #if false // Afficher disques physiques et paritions logiques ManagementObjectCollection partitions = new ManagementObjectSearcher( @"Select * From Win32_DiskPartition " + "Where DeviceID = 'Disk #0, Partition #0'").Get(); foreach (ManagementObject partition in partitions) { ManagementObjectCollection diskDrives = new ManagementObjectSearcher ("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} " + "WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get(); foreach (ManagementObject diskDrive in diskDrives) { foreach (PropertyData property in diskDrive.Properties) { if (!property.IsArray) Console.WriteLine("Disque {0} : {1}", property.Name, property.Value); } } } #endif }
/// <summary> /// 主板编号 /// </summary> /// <returns></returns> public string GetMainBoardId() { string result = ""; ManagementObjectSearcher searcher = new ManagementObjectSearcher("rootCIMV2", "SELECT * FROM Win32_BaseBoard"); ManagementObjectCollection moCollection = searcher.Get(); foreach (ManagementObject mObject in moCollection) { result += mObject["SerialNumber"].ToString() + " "; } return result; }
// <summary> // Read the serial number from the hard disk that keep the bootable partition (boot disk) // </summary> // <returns> // If succedes, returns the string rappresenting the Serial Number. // String.Empty if it fails. // </returns> private static string getHddSerialNumber() { // --- Win32 Disk ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\root\\cimv2", "select * from Win32_DiskPartition WHERE BootPartition=True"); uint diskIndex = 999; foreach (ManagementObject partition in searcher.Get()) { diskIndex = Convert.ToUInt32(partition["Index"]); break; // TODO: might not be correct. Was : Exit For } // I haven't found the bootable partition. Fail. if (diskIndex == 999) return string.Empty; // --- Win32 Disk Drive searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive where Index = " + diskIndex.ToString()); string deviceName = ""; foreach (ManagementObject wmi_HD in searcher.Get()) { deviceName = wmi_HD["Name"].ToString(); break; // TODO: might not be correct. Was : Exit For } // I haven't found the disk drive. Fail if (string.IsNullOrEmpty(deviceName.Trim())) return string.Empty; // -- Some problems in query parsing with backslash. Using like operator if (deviceName.StartsWith("\\\\.\\")) { deviceName = deviceName.Replace("\\\\.\\", "%"); } // --- Physical Media searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia WHERE Tag like '" + deviceName + "'"); string serial = string.Empty; foreach (ManagementObject wmi_HD in searcher.Get()) { serial = wmi_HD["SerialNumber"].ToString(); break; // TODO: might not be correct. Was : Exit For } return serial; }
/// <summary> /// 查询硬盘编号 /// </summary> /// <returns></returns> public string GetMainHardDiskId() { string result = ""; ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia"); ManagementObjectCollection moCollection = searcher.Get(); foreach (ManagementObject mObject in moCollection) { result += mObject["SerialNumber"].ToString() + " "; } return result; }
/// <summary> /// 主板编号 /// </summary> /// <returns></returns> public string GetNetworkAdapterId() { string result = ""; ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT MACAddress FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL)AND (Manufacturer <> 'Microsoft'))"); ManagementObjectCollection moCollection = searcher.Get(); foreach (ManagementObject mObject in moCollection) { result += mObject["MACAddress"].ToString() + " "; } return result; }
// Keep from having all clients synced private void DelayStart() { try { // Read the clock speed of the processor and use it as a seed so // on windows update, when all the clients restart, they don't sync int nSeed = 0; ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Processor"); ManagementObjectCollection col = searcher.Get(); foreach (ManagementObject oCur in col) { foreach (PropertyData Data in oCur.Properties) { string sCur = Data.Name as string; if (sCur != null) if (sCur == "CurrentClockSpeed") { nSeed = Convert.ToInt32(Data.Value); } } } Random rand = new Random(nSeed); nSeed = rand.Next(100, 1000); WriteToLog("Delaying start by: " + Convert.ToString(nSeed) + " milliseconds"); System.Threading.Thread.Sleep(nSeed); } catch (Exception Ex) { } }
static void GetWMIStats() { long mb = 1048576; //megabyte in # of bytes 1024x1024 //Connection credentials to the remote computer - not needed if the logged in account has access ConnectionOptions oConn = new ConnectionOptions(); //oConn.Username = "******"; //oConn.Password = "******"; System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\localhost", oConn); //get Fixed disk stats System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3"); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs,oQuery); ManagementObjectCollection oReturnCollection = oSearcher.Get(); //variables for numerical conversions double fs = 0; double us = 0; double tot = 0; double up = 0; double fp = 0; //for string formating args object[] oArgs = new object[2]; Console.WriteLine("*******************************************"); Console.WriteLine("Hard Disks"); Console.WriteLine("*******************************************"); //loop through found drives and write out info foreach( ManagementObject oReturn in oReturnCollection ) { // Disk name Console.WriteLine("Name : " + oReturn["Name"].ToString()); //Free space in MB fs = Convert.ToInt64(oReturn["FreeSpace"])/mb; //Used space in MB us = (Convert.ToInt64(oReturn["Size"]) - Convert.ToInt64(oReturn["FreeSpace"]))/mb; //Total space in MB tot = Convert.ToInt64(oReturn["Size"])/mb; //used percentage up = us/tot * 100; //free percentage fp = fs/tot * 100; //used space args oArgs[0] = (object)us; oArgs[1] = (object)up; //write out used space stats Console.WriteLine("Used: {0:#,###.##} MB ({1:###.##})%", oArgs); //free space args oArgs[0] = fs; oArgs[1] = fp; //write out free space stats Console.WriteLine("Free: {0:#,###.##} MB ({1:###.##})%", oArgs); Console.WriteLine("Size : {0:#,###.##} MB", tot); Console.WriteLine("*******************************************"); } // Get process info including a method to return the user who is running it oQuery = new System.Management.ObjectQuery("select * from Win32_Process"); oSearcher = new ManagementObjectSearcher(oMs,oQuery); oReturnCollection = oSearcher.Get(); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("*******************************************"); Console.WriteLine("Processes"); Console.WriteLine("*******************************************"); Console.WriteLine(""); //loop through each process - I limited it to first 6 so the DOS buffer would not overflow and cut off the disk stats int i=0; foreach( ManagementObject oReturn in oReturnCollection ) { if(i==6) break; i++; Console.WriteLine("*******************************************"); Console.WriteLine(oReturn["Name"].ToString().ToLower()); Console.WriteLine("*******************************************"); //arg to send with method invoke to return user and domain - below is link to SDK doc on it //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/getowner_method_in_class_win32_process.asp?frame=true string[] o = new String[2]; oReturn.InvokeMethod("GetOwner",(object[])o); //write out user info that was returned Console.WriteLine("User: "******"\\" + o[0]); Console.WriteLine("PID: " + oReturn["ProcessId"].ToString()); //get priority if(oReturn["Priority"] != null) Console.WriteLine("Priority: " + oReturn["Priority"].ToString()); //get creation date - need managed code function to convert date - if(oReturn["CreationDate"] != null) { try { //get datetime string and convert string s = oReturn["CreationDate"].ToString(); DateTime dc = ToDateTime(s); //write out creation date Console.WriteLine("CreationDate: " + dc.AddTicks(-TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Ticks).ToLocalTime().ToString()); } //just in case - I was getting a weird error on some entries catch(Exception err) { Console.WriteLine(err.Message); } } //this is the amount of memory used if(oReturn["WorkingSetSize"] != null) { long mem = Convert.ToInt64(oReturn["WorkingSetSize"].ToString()) / 1024; Console.WriteLine("Mem Usage: {0:#,###.##}Kb",mem); } Console.WriteLine(""); } }
private static List<List<string>> FindAllDevices() { List<List<string>> devices = new List<List<string>>(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + "Win32_USBControllerDevice"); ManagementObjectSearcher searcher2 = new ManagementObjectSearcher("select * from " + "Win32_PnPEntity"); foreach (ManagementObject device in searcher.Get()) { string dev = device.ToString(); int pos1 = dev.IndexOf("VID_"); int pos2 = dev.IndexOf("PID_"); if (pos1 >= 0 && pos2 >= 0) { List<string> props = new List<string>(); props.Add(dev.Substring(pos1+4,4)); props.Add(dev.Substring(pos2+4,4)); bool found = false; foreach (List<string> i in devices) { if (i[0] == props[0] && i[1] == props[1]) found = true; } if (!found) { string description = "Unknown"; foreach (ManagementObject device2 in searcher2.Get()) { string search = dev.Substring(pos1, 17); if (device2.ToString().IndexOf(search) >= 0) { description = (string)device2.GetPropertyValue("Caption"); } } props.Add(description); devices.Add(props); } } } return devices; }
protected void Page_Load(object sender, EventArgs e) { SearchQuery = "SELECT Name, CommandLine,Caption, Description, ExecutablePath FROM Win32_Process"; var searcher = new ManagementObjectSearcher(SearchQuery); SearchResult = searcher.Get().toList().str(); }
public static string GetPhysicalMemory() { ManagementScope oMs = new ManagementScope(); ObjectQuery oQuery = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory"); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery); ManagementObjectCollection oCollection = oSearcher.Get(); long MemSize = 0; long mCap = 0; // In case more than one Memory sticks are installed foreach (ManagementObject obj in oCollection) { mCap = Convert.ToInt64(obj["Capacity"]); MemSize += mCap; } MemSize = (MemSize / 1024) / 1024; return MemSize.ToString() + "MB"; }
private IEnumerable<ManagementObject> GetWmiObject(string query, string machineName, string rootPath) { try { var conn = new ConnectionOptions(); var path = string.Format(@"\\{0}\{1}", machineName, rootPath); if (!string.IsNullOrEmpty(this.Username)) { conn.Username = this.Username; } var pwd = this.Decrypt(this.Password); if (!string.IsNullOrEmpty(pwd)) { conn.Password = pwd; } path = string.Format(@"\\{0}\{1}", this.Hostname, rootPath); var scope = new ManagementScope(path, conn); this.Log.Debug(string.Format("{0} {1}", path, query)); var queryObject = new ObjectQuery(query); var searcher = new ManagementObjectSearcher(scope, queryObject); return searcher.Get().Cast<ManagementObject>().ToList(); } catch (Exception e) { this.Log.Debug(e); throw; } }
public static void Main() { myCounter = new PerformanceCounter("Processor", @"% Processor Time", @"_Total"); try { myCounter.NextValue().ToString(); Thread.Sleep(100); Console.WriteLine("cpuPercentUsage=" + myCounter.NextValue().ToString()); } catch { return; } try { ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature"); int i = 0; foreach (ManagementObject obj in searcher.Get()) { Double temp = Convert.ToDouble(obj["CurrentTemperature"].ToString()); temp = (temp - 2732) / 10.0; Console.WriteLine("cpuTemp" + i++ + "=" + temp); } } catch { return; } }