protected virtual void GetOperatingSystemInfo(string Name, string UserName, string Password) { if (string.IsNullOrEmpty(Name)) throw new ArgumentNullException("Name"); ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempNetworkAdapter in Collection) { if (TempNetworkAdapter.Properties["LastBootUpTime"].Value != null) { LastBootUpTime = ManagementDateTimeConverter.ToDateTime(TempNetworkAdapter.Properties["LastBootUpTime"].Value.ToString()); } } } } }
public bool GetNetEnabled(string adapter_desc) { string strWQuery = "SELECT DeviceID, ProductName, Description, " + "NetEnabled, NetConnectionStatus " + "FROM Win32_NetworkAdapter " + "WHERE Manufacturer <> 'Microsoft' "; ObjectQuery oQuery = new System.Management.ObjectQuery(strWQuery); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery); ManagementObjectCollection oReturnCollection = oSearcher.Get(); bool value = false; foreach (ManagementObject mo in oReturnCollection) { string description = mo["Description"] as string; if (adapter_desc.Contains(description)) { try { value = Convert.ToBoolean(mo["NetEnabled"]); if (value) { return(value); } } catch { } } } return(value); }
public static bool HasJobs() { bool hasJob = false; Console.WriteLine("Retrieving printer queue information using WMI"); Console.WriteLine("=================================="); //Query printer queue System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_PrintJob"); using (ManagementObjectSearcher query1 = new ManagementObjectSearcher(oq)) { using (ManagementObjectCollection queryCollection1 = query1.Get()) { hasJob = queryCollection1 != null && queryCollection1.Count > 0; //foreach (ManagementObject mo in queryCollection1) //{ // foreach (var prop in mo.Properties) // { // if (mo != null && mo[prop.Name] != null) // { // Console.WriteLine("Printer|" + prop.Name + ": " + mo[prop.Name] != null ? mo[prop.Name].ToString() : ""); // Console.WriteLine("=================================="); // } // } if (mo != null) // { // Console.WriteLine("Printer Driver : " + mo["DriverName"].ToString()); // Console.WriteLine("Document Name : " + mo["Document"].ToString()); // Console.WriteLine("Document Owner : " + mo["Owner"].ToString()); // Console.WriteLine("=================================="); // } //} } } return(hasJob); }
private void Run2() { ObjectQuery PerfRawDataQuery = new System.Management.ObjectQuery( "SELECT Name, InterruptsPersec, PercentIdleTime, PercentPrivilegedTime, PercentProcessorTime, PercentUserTime " + "FROM Win32_PerfFormattedData_PerfOS_Processor" ); ObjectQuery win32ProcQuery = new System.Management.ObjectQuery("SELECT Name from Win32_Processor"); using (ManagementObjectSearcher win32Proc = new ManagementObjectSearcher(win32ProcQuery), PerfRawData = new ManagementObjectSearcher(PerfRawDataQuery)) { var ob = win32Proc.Get().OfType <ManagementObject>().First(); Console.WriteLine($"Name!!: {ob["Name"]}"); foreach (ManagementObject obj in PerfRawData.Get()) { Console.WriteLine("-----------------------------------"); Console.WriteLine($"Name: {obj["Name"]}"); Console.WriteLine($"Прерываний/сек: {obj["InterruptsPersec"]}"); Console.WriteLine($"Процент времени бездействия: {obj["PercentIdleTime"]}"); Console.WriteLine($"% работы в привилегированном режиме: {obj["PercentPrivilegedTime"]}"); Console.WriteLine($"% загруженности процессора: {obj["PercentProcessorTime"]}"); Console.WriteLine($"% работы в пользовательском режиме: {obj["PercentUserTime"]}"); } } }
/// <summary> /// Kap numrin serial te hard diskut te pare qe eshte i instaluar dhe ka numer serial te vlefshem /// KUJDES!!! Duhet qe te testohet kur ne kompjutera perdoret Norton Ghost /// </summary> /// <returns>numrin serial qe kap nga Windowsi</returns> private static string GetHardDiskSignature() { try { ManagementObjectSearcher query; ManagementObjectCollection queryCollection; System.Management.ObjectQuery oq; ConnectionOptions co = new ConnectionOptions(); ManagementScope ms = new ManagementScope("\\\\localhost\\root\\cimv2", co); oq = new System.Management.ObjectQuery("SELECT * FROM Win32_DiskDrive"); query = new ManagementObjectSearcher(ms, oq); queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { if (mo["Signature"] != null) { if (mo["Signature"].ToString().Length > 8) { string id = mo["Signature"].ToString(); return(id.Substring(id.Length - 8, 8)); } return(Convert.ToInt64(mo["Signature"]).ToString("00000000")); } } return("00000001"); } catch (Exception ex) { return("00000001"); } }
/// <summary> /// Updates the list of cameras /// </summary> /// <returns>The list of cameras</returns> public static ManagementObjectCollection UpdateCameraList() { //Searches for the device using its name ObjectQuery oq = new System.Management.ObjectQuery("select * from Win32_PnPEntity where Name='NaturalPoint OptiTrack V100'"); ManagementObjectSearcher query = new ManagementObjectSearcher(oq); ManagementObjectCollection queryCollection = query.Get(); /* * Console.WriteLine(); * Console.WriteLine("Number of Cameras : " + queryCollection.Count); * if (queryCollection.Count > 0) * { * foreach (ManagementObject mo in queryCollection) * { * Console.WriteLine(); * Console.WriteLine("USB Camera"); * * * * foreach (PropertyData propertyData in mo.Properties) * { * * * Console.WriteLine("Property Name = " + propertyData.Name); * * Console.WriteLine("Property Value = " + propertyData.Value); * * } * * } * } */ return(queryCollection); }
public void SetEnabled(string adapter_desc) { string strWQuery = "SELECT DeviceID, ProductName, Description, " + "NetEnabled, NetConnectionStatus " + "FROM Win32_NetworkAdapter " + "WHERE Manufacturer <> 'Microsoft' "; ObjectQuery oQuery = new System.Management.ObjectQuery(strWQuery); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery); ManagementObjectCollection oReturnCollection = oSearcher.Get(); foreach (ManagementObject mo in oReturnCollection) { string description = mo["Description"] as string; if (adapter_desc.Contains(description)) { try { mo.InvokeMethod("Enable", null); } catch { } } } }
public List<Process> FindProcess(string name, string remotemachine) { if ( String.IsNullOrEmpty(remotemachine)) { return FindProcessOnLocalMachine(name); } ManagementScope scope = new ManagementScope("\\\\" + remotemachine + "\\root\\cimv2"); scope.Connect(); var result = new List<Process>(); string wmiQuery = string.Format("select ProcessId, CommandLine from Win32_Process where Name='{0}'", name); ObjectQuery query = new ObjectQuery(wmiQuery); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection retObjectCollection = searcher.Get(); foreach (ManagementObject retObject in retObjectCollection) { string commandline = retObject["CommandLine"] as string; string[] cols = commandline.Split('-'); var pid = retObject["ProcessId"]; var p = new Process() { Pid = (uint)retObject["ProcessId"], Name = cols[1].Substring(3).Replace('"',' ' ) }; result.Add(p); } return result; }
public static string GetNiceName(string port) { if (serialportproblem) return ""; DateTime start = DateTime.Now; try { ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject obj2 in searcher.Get()) { //DeviceID if (obj2.Properties["DeviceID"].Value.ToString().ToUpper() == port.ToUpper()) { DateTime end = DateTime.Now; if ((end - start).TotalSeconds > 5) serialportproblem = true; return obj2.Properties["Name"].Value.ToString(); } } } catch { } return ""; }
public void DeleteShare(IShareDescriptor descriptor) { var wqlQuery = new ObjectQuery(string.Format(@"SELECT * from Win32_Share WHERE Name = '{0}'", descriptor.Name)); ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(_managementClass.Scope, wqlQuery); ManagementObjectCollection shareObjectsCollection = objectSearcher.Get(); if (shareObjectsCollection.Count == 0) { throw new ShareInstrumentationException(@"{0} {1}.", ExceptionMessages.Win32_ShareNotFound, descriptor.Name); } foreach (ManagementObject shareObject in shareObjectsCollection) { PropertyDataCollection outParams; long returnValue; var inParamsCollection = new List<PropertyDataObject>(); inParamsCollection.Add(new PropertyDataObject() { Name = "Reason", Value = (uint)0 }); _handler.Handle("Terminate", inParamsCollection, out outParams); returnValue = long.Parse(outParams["ReturnValue"].Value.ToString()); if (returnValue != 0) { throw new ShareInstrumentationException(@"{0} {1}.", ExceptionMessages.Win32_ShareFail, _errorMessageProvider.GetErrorMessage(ErrorMessageProvider.ErrorClass.Win32_Share, returnValue)); } } }
public static bool isAdmin(string processName) { string ProcessOwner = ""; string ProcessDomain = ""; System.Management.ObjectQuery x = new System.Management.ObjectQuery("Select * From Win32_Process where Name='" + processName + ".exe" + "'"); System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(x); foreach (System.Management.ManagementObject mo in mos.Get()) { string[] s = new string[2]; mo.InvokeMethod("GetOwner", (object[])s); ProcessOwner = s[0].ToString(); ProcessDomain = s[1].ToString(); break; } string userPath = ProcessDomain + "/" + ProcessOwner; using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group")) { foreach (object member in (IEnumerable)groupEntry.Invoke("Members")) { using (DirectoryEntry memberEntry = new DirectoryEntry(member)) { Console.WriteLine(memberEntry.Path); if (memberEntry.Path.Contains(userPath)) { return true; } } } } return false; }
/// <summary> /// 重启指定服务 /// </summary> /// <param name="serviceName"></param> /// <param name="ip"></param> public static void RestartService(string serviceName, string ip) { var co = new ConnectionOptions(); if (!string.IsNullOrEmpty(UserName)) { co.Username = Domain + "\\" + UserName; //连接需要的用户名 co.Password = PassWord; //连接需要的密码 } string connectString = $@"SELECT * FROM Win32_Service WHERE Name='{serviceName}'"; //查询字符串 System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + ip + "\\root\\cimv2", co); var oq = new System.Management.ObjectQuery(connectString); var query = new ManagementObjectSearcher(ms, oq); var queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { mo.InvokeMethod("StopService", null); mo.Put(); mo.InvokeMethod("StartService", null); mo.Put(); } }
/// <summary> /// Kap daten kur eshte instaluar sistemi i shfrytezimit ne kete kompjuter /// </summary> /// <returns></returns> private static string GetSystemDateInstalled() { try { ManagementObjectSearcher query; ManagementObjectCollection queryCollection; System.Management.ObjectQuery oq; string dateInstalledString = ""; ConnectionOptions co = new ConnectionOptions(); ManagementScope ms = new ManagementScope("\\\\localhost\\root\\cimv2", co); oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); query = new ManagementObjectSearcher(ms, oq); queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { if (mo["InstallDate"] != null) { dateInstalledString = mo["InstallDate"].ToString(); } } return(dateInstalledString); } catch { return(""); } }
public static String[] getComputerInfos(string computername) { String[] computerInfos = new String[2]; ConnectionOptions connOptions = new ConnectionOptions(); ObjectGetOptions objectGetOptions = new ObjectGetOptions(); ManagementPath managementPath = new ManagementPath("Win32_Process"); //To use caller credential connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", computername), connOptions); manScope.Connect(); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(manScope, query); ManagementObjectCollection queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection){ computerInfos[0] = Convert.ToString(m["Caption"]); computerInfos[1] = Convert.ToString(m["Status"]); } return computerInfos; }
private static List <string> GetPrinters() { List <string> printerNames = new List <string>(); // Use the ObjectQuery to get the list of configured printers System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection moc = mosearcher.Get(); foreach (ManagementObject mo in moc) { System.Management.PropertyDataCollection pdc = mo.Properties; foreach (System.Management.PropertyData pd in pdc) { if (!(bool)mo["Network"]) { bool bExists = printerNames.Contains(mo["DeviceID"].ToString()); if (!bExists) { printerNames.Add(mo["DeviceID"].ToString()); } } } } return(printerNames); }
public void Delete(IPHostEntry host, DirectoryInfo target) { var wqlQuery = new ObjectQuery(string.Format(@"SELECT * from Win32_Directory WHERE Name = '{0}'", target.Name)); var managementClassEntry = _managementClassList.First(x => x.Item1 == _hostsList.IndexOf(host)); ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(managementClassEntry.Item2.Scope, wqlQuery); ManagementObjectCollection directoryObjectsCollection = objectSearcher.Get(); if (directoryObjectsCollection.Count == 0) { throw new FileSystemInstrumentationException(@"{0} {1}.", ExceptionMessages.Win32_DirectoryFail, target.Name); } foreach (ManagementObject shareObject in directoryObjectsCollection) { PropertyDataCollection outParams; long returnValue; managementClassEntry.Item3.Handle("Delete", new List<PropertyDataObject>(), out outParams); returnValue = long.Parse(outParams["ReturnValue"].Value.ToString()); if (returnValue != 0) { throw new FileSystemInstrumentationException(@"{0} {1}.", ExceptionMessages.Win32_DirectoryFail, _errorMessageProvider.GetErrorMessage(ErrorMessageProvider.ErrorClass.Win32_Directory, returnValue)); } } }
/// <summary> /// Updates the list of cameras /// </summary> /// <returns>The list of cameras</returns> public static ManagementObjectCollection UpdateCameraList() { //Searches for the device using its name ObjectQuery oq = new System.Management.ObjectQuery("select * from Win32_PnPEntity where Name='NaturalPoint OptiTrack V100'"); ManagementObjectSearcher query = new ManagementObjectSearcher(oq); ManagementObjectCollection queryCollection = query.Get(); /* Console.WriteLine(); Console.WriteLine("Number of Cameras : " + queryCollection.Count); if (queryCollection.Count > 0) { foreach (ManagementObject mo in queryCollection) { Console.WriteLine(); Console.WriteLine("USB Camera"); foreach (PropertyData propertyData in mo.Properties) { Console.WriteLine("Property Name = " + propertyData.Name); Console.WriteLine("Property Value = " + propertyData.Value); } } } */ return queryCollection; }
public static String getUID() { try { ManagementScope theScope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2"); StringBuilder theQueryBuilder = new StringBuilder(); theQueryBuilder.Append("SELECT MACAddress FROM Win32_NetworkAdapter"); ObjectQuery theQuery = new ObjectQuery(theQueryBuilder.ToString()); ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery); ManagementObjectCollection theCollectionOfResults = theSearcher.Get(); foreach (ManagementObject theCurrentObject in theCollectionOfResults) { if (theCurrentObject != null && theCurrentObject["MACAddress"] != null) { return theCurrentObject["MACAddress"].ToString(); } } } catch (Exception ex) { return "undefined"; } return "undefined"; }
/// <summary> /// Gets the physcial cores and should this fail returns the Environment.ProcessorCount /// that can also include logical cores. /// </summary> /// <returns>core count.</returns> public static uint GetPhysicalCores() { try { ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2"); ObjectQuery query = new ObjectQuery("SELECT NumberOfCores FROM Win32_Processor"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection queryCollection = searcher.Get(); var enumerator = queryCollection.GetEnumerator(); if (enumerator.MoveNext()) { ManagementObject obj = (ManagementObject)enumerator.Current; return (uint)obj["NumberOfCores"]; } else return (uint)Environment.ProcessorCount; } // We are not very interested in throwing the exception, we might log it // but this carries little information as if WMI fails there is very little // that the we or the user can do to provide the correct information. catch { return (uint)Environment.ProcessorCount; } }
public static List<EntStartUp>GetStartUpDetails(ManagementScope scope) { _logger.Info("Collecting startup details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntStartUp> lstStartUp = new List<EntStartUp>(); try { query = new ObjectQuery("select * from Win32_StartupCommand where User != '.DEFAULT' and User != 'NT AUTHORITY\\\\SYSTEM'"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstStartUp.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstStartUp.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception in startup collection " + e.Message); } finally { searcher.Dispose(); } return lstStartUp; }
private static string FindPhysicalDrive(string path) { FileSystemInfo iDirectory = null; var wmiQuery = new ObjectQuery("SELECT Antecedent, Dependent FROM Win32_LogicalDiskToPartition"); var wmiSearcher = new ManagementObjectSearcher(wmiQuery); var iFile = new FileInfo(path); try { if ((iFile.Attributes & FileAttributes.Directory) == FileAttributes.Directory) { iDirectory = new DirectoryInfo(iFile.FullName); } else { iDirectory = iFile; throw new FormatException("Argument is not a directory."); } } catch (IOException) { iDirectory = new DirectoryInfo(iFile.FullName); } var wmiPhysicalDiskNumber = -1; foreach (var iReturn in wmiSearcher.Get()) { var disk = GetSubsubstring((string)iReturn["Antecedent"], "Win32_DiskPartition.DeviceID", "Disk #", ","); var partition = GetSubsubstring((string)iReturn["Dependent"], "Win32_LogicalDisk.DeviceID", "", ""); if (iDirectory.Name.StartsWith(partition, StringComparison.InvariantCultureIgnoreCase)) { if (int.TryParse(disk, NumberStyles.Integer, CultureInfo.InvariantCulture, out wmiPhysicalDiskNumber)) { return @"\\?\PHYSICALDRIVE" + wmiPhysicalDiskNumber.ToString(CultureInfo.InvariantCulture); } else { throw new FormatException("Cannot retrieve physical disk number."); } } } return null; }
public static SelectList GetPrinterList() { List <SelectListItem> myPrinters = new List <SelectListItem>(); System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection printers = mosearcher.Get(); foreach (ManagementObject printer in printers) { /*var state = "(Available Online)"; * if (printer["WorkOffline"].ToString().ToLower().Equals("true")) * { * state = "(Available Offline)"; * } */ var emptyItem = new SelectListItem() { Value = printer["Name"].ToString(), Text = printer["Name"].ToString() //+" "+ state }; myPrinters.Add(emptyItem); } SelectList objselectlist = new SelectList(myPrinters, "Value", "Text"); return(objselectlist); }
void AddMotherboardInfo() { try { ObjectQuery MotherboardQuery = new System.Management.ObjectQuery("select Product, Caption, Description, SerialNumber, Manufacturer, Version from Win32_BaseBoard"); ManagementObjectSearcher MotherboardSearcher = new ManagementObjectSearcher(MotherboardQuery); ManagementObjectCollection MotherboardCollection = MotherboardSearcher.Get(); foreach (ManagementObject MotherboardInfo in MotherboardCollection) { InformString.Append(MotherboardInfo["Manufacturer"].ToString()); InformString.Append((char)13); InformString.Append((char)10); InformString.Append(MotherboardInfo["Product"].ToString()); InformString.Append((char)13); InformString.Append((char)10); InformString.Append(MotherboardInfo["SerialNumber"].ToString()); InformString.Append((char)13); InformString.Append((char)10); InformString.Append(MotherboardInfo["Version"].ToString()); InformString.Append((char)13); InformString.Append((char)10); } } catch { } }
private void tsbRun_Click(object sender, EventArgs e) { SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject os in searcher.Get()) { this.txtResult.AppendText(os["Name"] + ";"); } this.txtResult.AppendText("\r\n"); //连接远程计算机 ConnectionOptions co = new ConnectionOptions(); co.Username = "******"; co.Password = "******"; System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\192.168.100.51\\root\\cimv2", co); //查询远程计算机 System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms, oq); ManagementObjectCollection queryCollection1 = query1.Get(); foreach (ManagementObject mo in queryCollection1) { string[] ss = { "" }; mo.InvokeMethod("Reboot", ss); this.txtResult.AppendText(mo.ToString()); } }
private void DisplayRam(object sender, EventArgs e) { //In thong so trong tabMemry 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; long FreePhysicalMemory = 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; txtRam.Text = MemSize.ToString() + " MB"; // Get info RAM availble ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem"); foreach (ManagementObject tmp in searcher.Get()) { FreePhysicalMemory = Convert.ToInt64(tmp["FreePhysicalMemory"]); } FreePhysicalMemory = (FreePhysicalMemory) / 1024; txtRamAvai.Text = FreePhysicalMemory.ToString() + " MB"; }
/// <summary> /// Attempts to start the selected process. - BC /// </summary> /// <returns>Return value of the attempted command.</returns> public static int start(String program) { //MRM Get a list of all programs installed and basic information about them from Windows ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Product"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementObjectCollection collection = searcher.Get(); //MRM The closest filename and the full path to the file String full = null; String closest = null; //MRM Loop through all the programs installed foreach (ManagementObject mObject in collection) { //MRM See if this is the correct program to be looking at if (((String)mObject["name"]).ToLower() == program.ToLower() && (String)mObject["InstallLocation"] != null) { //MRM Get the install location for the application since it is the one we are looking for String[] fileNames = System.IO.Directory.GetFiles((String)mObject["InstallLocation"]); foreach (String fileName in fileNames) { //MRM Grab the actual filename to check String[] fileSplit = fileName.Split('\\'); String file = fileSplit[fileSplit.Length - 1]; //MRM Make sure the file is executable and is not meant for updating or installing the application if (file.Contains(".exe") && file.Substring(file.Length-4) == ".exe" && (!file.ToLower().Contains("update") && !file.ToLower().Contains("install"))) { //MRM Replace all underscored with spaces to make it more towards the normal file naming convention file = file.Replace("_", " "); //MRM Get the first part of the file before any extension of . due to standard naming conventions String[] fileNonTypes = file.Split('.'); file = fileNonTypes[0]; //MRM If there is no guess assume we are correct for now if (closest == null) { full = fileName; closest = file; } //MRM Else if the current file is closer than our previous guess, select that file else if (Math.Abs(program.CompareTo(closest)) >= Math.Abs(program.CompareTo(file))) { full = fileName; closest = file; } } } break; } } //MRM If we have found an adequte file to launch, launch the file. if (full != null) { //MRM Start a process with the correct information Process p = new Process(); p.StartInfo.RedirectStandardOutput = false; p.StartInfo.RedirectStandardInput = false; p.StartInfo.FileName = full; p.Start(); return 1; } return -1; }
/// <summary> /// Merr numrin serial te windows-it qe eshte instaluar ne kete kompjuter dhe nxjerr nga ky numer /// 10 shifrat e para pa shenjen '-'. Ne rast te ndonje gabimi kthen "1". /// Ky numer nuk eshte unik per cdo kompjuter, te pakten ne rastet kur perdoret Norton Ghost. /// </summary> /// <returns>10 shifrat e para te numrit serial te Windows-it</returns> private static string GetSystemSerial() { try { string serial = "0000000001"; ManagementObjectSearcher query; ManagementObjectCollection queryCollection; System.Management.ObjectQuery oq; ConnectionOptions co = new ConnectionOptions(); ManagementScope ms = new ManagementScope("\\\\localhost\\root\\cimv2", co); oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); query = new ManagementObjectSearcher(ms, oq); queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { if (mo["SerialNumber"] != null) { serial = mo["SerialNumber"].ToString(); break; } } char[] str = { }; if (serial.Replace("-", "").Length > 7) { serial = serial.Replace("-", ""); return(serial.Substring(serial.Length - 10, 10)); } return(serial); } catch { return("0000000001"); } }
private static Dictionary<string, double> DiskUsage() { Dictionary<string, double> temp = new Dictionary<string, double>(); double freeSpace = 0; double usedSpace = 0; // get disk stats System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3"); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery); ManagementObjectCollection oReturnCollection = oSearcher.Get(); //loop through found drives and write out info foreach (ManagementObject oReturn in oReturnCollection) { //Free space in MB freeSpace += Convert.ToInt64(oReturn["FreeSpace"]); //Used space in MB usedSpace += (Convert.ToInt64(oReturn["Size"]) - Convert.ToInt64(oReturn["FreeSpace"])); } temp.Add("used", usedSpace); temp.Add("free", freeSpace); return temp; }
public static List<Object[]> checkAntiVirus() { List<Object[]> av = new List<Object[]>(); ConnectionOptions _connectionOptions = new ConnectionOptions(); _connectionOptions.EnablePrivileges = true; _connectionOptions.Impersonation = ImpersonationLevel.Impersonate; ManagementScope _managementScope = new ManagementScope(string.Format("\\\\{0}\\root\\SecurityCenter2", "localhost"), _connectionOptions); _managementScope.Connect(); ObjectQuery _objectQuery = new ObjectQuery("SELECT * FROM AntivirusProduct"); ManagementObjectSearcher _managementObjectSearcher = new ManagementObjectSearcher(_managementScope, _objectQuery); ManagementObjectCollection _managementObjectCollection = _managementObjectSearcher.Get(); if (_managementObjectCollection.Count > 0) { Boolean updated = false; foreach (ManagementObject item in _managementObjectCollection) { updated = (item["productState"].ToString() == "266240" || item["productState"].ToString() == "262144"); av.Add(new Object[] { item["displayName"].ToString(), updated }); } } return av; }
private static Dictionary <string, double> DiskUsage() { Dictionary <string, double> temp = new Dictionary <string, double>(); double freeSpace = 0; double usedSpace = 0; // get disk stats System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3"); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery); ManagementObjectCollection oReturnCollection = oSearcher.Get(); //loop through found drives and write out info foreach (ManagementObject oReturn in oReturnCollection) { //Free space in MB freeSpace += Convert.ToInt64(oReturn["FreeSpace"]); //Used space in MB usedSpace += (Convert.ToInt64(oReturn["Size"]) - Convert.ToInt64(oReturn["FreeSpace"])); } temp.Add("used", usedSpace); temp.Add("free", freeSpace); return(temp); }
/// <summary> /// Loads the BIOS info /// </summary> /// <param name="Name">Computer name</param> /// <param name="UserName">User name</param> /// <param name="Password">Password</param> private void LoadBIOS(string Name, string UserName, string Password) { ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_BIOS"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempBIOS in Collection) { SerialNumber = TempBIOS.Properties["Serialnumber"].Value.ToString(); } } } }
// kernel load percentage public static List <Dictionary <string, string> > GetPerfOS() { List <Dictionary <string, string> > perfOS = new List <Dictionary <string, string> >(); ObjectQuery PerfRawDataQuery = new System.Management.ObjectQuery( "SELECT Name, InterruptsPersec, PercentIdleTime, PercentPrivilegedTime, PercentProcessorTime, PercentUserTime " + "FROM Win32_PerfFormattedData_PerfOS_Processor" ); using (ManagementObjectSearcher PerfRawData = new ManagementObjectSearcher(PerfRawDataQuery)) { foreach (ManagementObject obj in PerfRawData.Get()) { perfOS.Add( new Dictionary <string, string> { ["Name"] = obj["Name"].ToString(), ["InterruptsPersec"] = obj["InterruptsPersec"].ToString(), ["PercentIdleTime"] = obj["PercentIdleTime"].ToString(), ["PercentPrivilegedTime"] = obj["PercentPrivilegedTime"].ToString(), ["PercentProcessorTime"] = obj["PercentProcessorTime"].ToString(), ["PercentUserTime"] = obj["PercentUserTime"].ToString(), }); } }; return(perfOS); }
private void butShare_Click(object sender, EventArgs e) { // Соединяемся с удаленной машиной ConnectionOptions options = new ConnectionOptions(); options.Username = @"gamma\admin"; options.Password = "******"; //ManagementScope scope = // new ManagementScope( // "\\\\mymachine\\root\\cimv2", options); // для локальной машины ManagementScope scope = new ManagementScope( "\\\\localhost\\root\\cimv2"); scope.Connect(); // Делаем запрос к удаленной машине System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_Share"); ManagementObjectSearcher find = new ManagementObjectSearcher(scope, oq); string nl = Environment.NewLine; foreach (ManagementObject mo in find.Get()) { textBox1.Text = ("Список общих ресурсов = " + mo["Name"]) + nl; } }
public static bool isAdmin(string processName) { string ProcessOwner = ""; string ProcessDomain = ""; System.Management.ObjectQuery x = new System.Management.ObjectQuery("Select * From Win32_Process where Name='" + processName + ".exe" + "'"); System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(x); foreach (System.Management.ManagementObject mo in mos.Get()) { string[] s = new string[2]; mo.InvokeMethod("GetOwner", (object[])s); ProcessOwner = s[0].ToString(); ProcessDomain = s[1].ToString(); break; } string userPath = ProcessDomain + "/" + ProcessOwner; using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group")) { foreach (object member in (IEnumerable)groupEntry.Invoke("Members")) { using (DirectoryEntry memberEntry = new DirectoryEntry(member)) { Console.WriteLine(memberEntry.Path); if (memberEntry.Path.Contains(userPath)) { return(true); } } } } return(false); }
public static List<COMPortFinder> GetCOMPortsInfo() { List<COMPortFinder> COMPortFinderList = new List<COMPortFinder>(); 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")) { COMPortFinder COMPortFinder = new COMPortFinder(); COMPortFinder.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty); COMPortFinder.Description = caption; COMPortFinderList.Add(COMPortFinder); } } } } } return COMPortFinderList; }
public static Dictionary <String, Dictionary <String, String> > select(string request) { Dictionary <String, Dictionary <String, String> > result = new Dictionary <String, Dictionary <String, String> >(); System.Management.ObjectQuery aObjectQuery = new System.Management.ObjectQuery(request); ManagementObjectSearcher aManagementObjectSearcher = new ManagementObjectSearcher(new ManagementScope(), aObjectQuery); ManagementObjectCollection aManagementObjectCollection = aManagementObjectSearcher.Get(); foreach (ManagementObject mo in aManagementObjectCollection) { Dictionary <String, String> pResult = new Dictionary <String, String>(); foreach (PropertyData prop in mo.Properties) { if (!pResult.ContainsKey(prop.Name)) { if (prop.Value != null) { pResult.Add(prop.Name, prop.Value.ToString()); } else { pResult.Add(prop.Name, ""); } } } if (!result.ContainsKey(mo.Path.ToString())) { result.Add(mo.Path.ToString(), pResult); } } return(result); }
public void EnableAdapter(string adapterName, bool adapterStatus) { try { ManagementObject currentMObject = new ManagementObject(); string strWQuery = "SELECT DeviceID,ProductName,Description,NetEnabled " + "FROM Win32_NetworkAdapter "; ObjectQuery oQuery = new System.Management.ObjectQuery(strWQuery); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery); ManagementObjectCollection oReturnCollection = oSearcher.Get(); foreach (ManagementObject mo in oReturnCollection) { currentMObject = mo; if (adapterStatus) { if ((string)currentMObject["NetConnectionId"] == adapterName) { currentMObject.InvokeMethod("Enable", null); } else { currentMObject.InvokeMethod("Disable", null); } } else { currentMObject.InvokeMethod("Disable", null); } } } catch (Exception ex) {} }
static IEnumerable<byte[]> GetManagementObjects() { var options = new EnumerationOptions {Rewindable = false, ReturnImmediately = true}; var scope = new ManagementScope(ManagementPath.DefaultPath); var query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter"); var searcher = new ManagementObjectSearcher(scope, query, options); ManagementObjectCollection collection = searcher.Get(); foreach (ManagementObject obj in collection) { byte[] bytes; try { PropertyData propertyData = obj.Properties["MACAddress"]; string propertyValue = propertyData.Value.ToString(); bytes = propertyValue.Split(':') .Select(x => byte.Parse(x, NumberStyles.HexNumber)) .ToArray(); } catch (Exception) { continue; } if (bytes.Length == 6) yield return bytes; } }
public void GetFestplattenPLatz() { ManagementObjectSearcher query; ManagementObjectCollection queryCollection; System.Management.ObjectQuery oq; string stringMachineName = "localhost"; //Connect to the remote computer ConnectionOptions co = new ConnectionOptions(); //Point to machine System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + stringMachineName + "\\root\\cimv2", co); oq = new System.Management.ObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = 'C:'"); query = new ManagementObjectSearcher(ms, oq); queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { Console.WriteLine($"freier platz: {mo["FreeSpace"].ToString()}"); } }
public static List<EntHotfixes> GetHotfixDetails(ManagementScope scope) { _logger.Info("Collecting hotfix for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntHotfixes> lstHotfix = new List<EntHotfixes>(); try { query = new ObjectQuery("Select * from Win32_QuickFixEngineering"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstHotfix.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstHotfix.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception is hotfix collection " + e.Message); } finally { searcher.Dispose(); } return lstHotfix; }
private void butReboot_Click(object sender, EventArgs e) { // Соединяемся с удаленным компьюетром ConnectionOptions options = new ConnectionOptions(); options.Username = @"domen\admin"; options.Password = "******"; ManagementScope scope = new ManagementScope( "\\\\machine\\root\\cimv2", options); scope.Connect(); // Делаем запрос к удаленной машине System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher query1 = new ManagementObjectSearcher(scope, oq); ManagementObjectCollection queryCollection1 = query1.Get(); foreach (ManagementObject mo in queryCollection1) { string[] ss = { "" }; mo.InvokeMethod("Reboot", ss); this.Text = mo.ToString(); } }
/// <summary> /// Gets a list of files on the machine with a specific extension /// </summary> /// <param name="Computer">Computer to search</param> /// <param name="UserName">User name (if not local)</param> /// <param name="Password">Password (if not local)</param> /// <param name="Extension">File extension to look for</param> /// <returns>List of files that are found to have the specified extension</returns> public static IEnumerable<string> GetFilesWithExtension(string Computer, string UserName, string Password, string Extension) { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Computer), "Computer"); Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Extension), "Extension"); List<string> Files = new List<string>(); ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Computer + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Computer + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM CIM_DataFile where Extension='" + Extension + "'"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempBIOS in Collection) { Files.Add(TempBIOS.Properties["Drive"].Value.ToString()+TempBIOS.Properties["Path"].Value.ToString()+TempBIOS.Properties["FileName"].Value.ToString()); } } } return Files; }
public static List<EntEnvironmentVars>GetEnvironmentVarDetails(ManagementScope scope) { _logger.Info("Collecting Environment variable for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntEnvironmentVars> lstEnvVars = new List<EntEnvironmentVars>(); try { query = new ObjectQuery("Select * from Win32_Environment"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstEnvVars.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstEnvVars.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception is Environment var collection " + e.Message); } finally { searcher.Dispose(); } return lstEnvVars; }
public static bool IsBridge(string guid) { //find adapter in WMI and compare servicename ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2"); ObjectQuery query = new ObjectQuery("SELECT ServiceName, GUID FROM Win32_NetworkAdapter Where GUID = '" + guid + "'"); using (ManagementObjectSearcher netSearcher = new ManagementObjectSearcher(scope, query)) { using (ManagementObjectCollection netQueryCollection = netSearcher.Get()) { using (ManagementObjectCollection.ManagementObjectEnumerator netMOEn = netQueryCollection.GetEnumerator()) { if (netMOEn.MoveNext()) { ManagementObject netMO = (ManagementObject)netMOEn.Current; if (netMO["ServiceName"] == null) return false; string srvName = (string)netMO["ServiceName"]; if (srvName == oldBridge | srvName == newBridge) { return true; } } } } } return false; }
public string ReceiveEvent(ManagementScope scope) { string strSalida; strSalida = ""; try { ObjectQuery selectQuery = new System.Management.ObjectQuery("Select * from Lnl_AlarmDefinition"); //Instanciamos un buscador de objetos ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, selectQuery); //Usamos un foreach para la selección individual de cada uno de los procesos para añadirlos a un ListBox foreach (ManagementObject proceso in searcher.Get()) { //Console.Write("ID:" + proceso["ID"].ToString() + " - " + "Description:" + proceso["Description"].ToString() + "\n\r"); strSalida = strSalida + "ID:" + proceso["ID"].ToString() + " - " + "Description:" + proceso["Description"].ToString() + " - " + "TextInstructionName:" + proceso["TextInstructionName"].ToString() + Environment.NewLine; } return(strSalida); } catch (ManagementException err) { return(err.Message); } }
public static List<EntDisk>GetDiskDetails(ManagementScope scope) { _logger.Info("Collecting disk details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntDisk> lstDisk = new List<EntDisk>(); try { query = new ObjectQuery("Select * from Win32_DiskDrive"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstDisk.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstDisk.Add(FillDetails(obj)); obj.Dispose(); } } catch (Exception e) { _logger.Error("Exception is disk collection " + e.Message); } finally { searcher.Dispose(); } return lstDisk; }
internal static async Task<string> GetFriendlyName(string portName) { string result = portName; await Task.Run(() => { try { string upper = portName.ToUpper(); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject obj2 in searcher.Get()) { //DeviceID if (obj2.Properties["DeviceID"].Value.ToString().ToUpper() == upper) { result = obj2.Properties["Name"].Value.ToString(); break; } } } } catch { } }); return result; }
public static List<EntOS> GetOSDetails(ManagementScope scope) { _logger.Info("Collecting OS details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntOS> lstOS = new List<EntOS>(); try { query = new ObjectQuery("Select * from Win32_OperatingSystem"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstOS.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstOS.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception in OS collection " + e.Message); } finally { searcher.Dispose(); } return lstOS; }
public Resolution GetResolution() { Resolution resolution = new Resolution(); var managementScope = new ManagementScope(); managementScope.Connect(); var query = new System.Management.ObjectQuery("SELECT CurrentHorizontalResolution, CurrentVerticalResolution FROM Win32_VideoController"); var searcher = new System.Management.ManagementObjectSearcher(managementScope, query); var records = searcher.Get(); int width = 0; int height = 0; foreach (var record in records) { if (!int.TryParse(record.GetPropertyValue("CurrentHorizontalResolution").ToString(), out width)) { throw new Exception("Throw some exception"); } if (!int.TryParse(record.GetPropertyValue("CurrentVerticalResolution").ToString(), out height)) { throw new Exception("Throw some exception"); } } resolution.Height = height; resolution.Width = width; return(resolution); }
public static String[] GetOtherPrinterNames() { var query = new ObjectQuery("SELECT * FROM Win32_Printer"); var searcher = new ManagementObjectSearcher(query); int num = searcher.Get().Count; int count = 0; string[] otherprinters = new string[(num)]; foreach (ManagementObject mo in searcher.Get()) { if (((bool)mo["Default"]) == false) { string whole = mo["Name"] as string; if (whole.Contains("opsprint")) { string[] actual; actual = whole.Split('\\'); otherprinters[count] = actual[3]; } else if (whole.Contains("Fax") || whole.Contains("XPS") || whole.Contains("OneNote")) { otherprinters[count] = null; } else { otherprinters[count] = whole; } } count = count +1; } return otherprinters; }
public static String GetDefaultPrinterName() { { var query = new ObjectQuery("SELECT * FROM Win32_Printer"); var searcher = new ManagementObjectSearcher(query); foreach (ManagementObject mo in searcher.Get()) { if (((bool?)mo["Default"]) ?? false) { string whole = mo["Name"] as string; if (whole.Contains("opsprint")) { string[] actual; actual = whole.Split('\\'); return actual[3]; } else if (whole.Contains("Fax") || whole.Contains("XPS") || whole.Contains("OneNote")) return "none"; else return whole; } } return null; } }
public static string getUserName() { try { var x = ""; var connectionOptions = new ConnectionOptions(); var scope = new System.Management.ManagementScope("\\\\localhost", connectionOptions); var query = new System.Management.ObjectQuery("select * from Win32_ComputerSystem"); using (var searcher = new ManagementObjectSearcher(scope, query)) { var builder = new System.Text.StringBuilder(); builder.Append(x); foreach (var row in searcher.Get()) { builder.Append((row["UserName"].ToString() + " ")); } x = builder.ToString(); return x; } } catch (Exception ex) { return ""; } }
// *** execute a query and return results *** public void Query(String wql) { try { // *** execute query *** Verbose(VerbosityLevel.Info, "[WMI] Executing query: " + wql); System.Management.ObjectQuery query = new System.Management.ObjectQuery(wql); ManagementObjectSearcher searcher = new ManagementObjectSearcher(ManagementScope, query); // *** get results *** ResultCollection = searcher.Get(); if (ResultCollection.Count > 0) { Verbose(VerbosityLevel.Info, "[WMI] Query succeeded"); } } // *** rpc server unavailable *** catch (System.Runtime.InteropServices.COMException e) { FatalError(StatusCode.Critical, "[WMI]", e.Message); } // *** bad username/password *** catch (System.UnauthorizedAccessException e) { FatalError(StatusCode.Critical, "[WMI]", e.Message); } // *** bad query *** catch (System.Management.ManagementException e) { FatalError(StatusCode.Critical, "[WMI]", e.Message); } }
/// <summary> /// Merr te dhenat e sistemit te shfrytezimit dhe te kompjuterit. /// </summary> private void SystemInfo() { try { ManagementObjectSearcher query; ManagementObjectCollection queryCollection; System.Management.ObjectQuery oq; string stringMachineName = "localhost"; //Krijon lidhjen me kompjuterin ConnectionOptions co = new ConnectionOptions(); //Shenjon te makina System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + stringMachineName + "\\root\\cimv2", co); // Marrim te dhenat nga sistemi i shfrytezimit per llojin e sistemit dhe emrin oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); query = new ManagementObjectSearcher(ms, oq); queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { lblSistemi.Text = mo["Caption"].ToString(); lblEmriPC.Text = mo["csname"].ToString(); } // Marrim informacionet per procesorin oq = new System.Management.ObjectQuery("SELECT * FROM Win32_processor"); query = new ManagementObjectSearcher(ms, oq); queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { this.lblEmriProcesori.Text = mo["Caption"].ToString(); this.lblLlojProcesori.Text = mo["Manufacturer"].ToString(); this.lblShpejtesiaProcesorit.Text = formatSpeed(Int64.Parse(mo["MaxClockSpeed"].ToString())); } //Marrim te dhenat per karten grafike oq = new System.Management.ObjectQuery("SELECT * FROM Win32_VideoController"); query = new ManagementObjectSearcher(ms, oq); queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { this.lblKartaGrafike.Text = mo["Name"].ToString(); if (mo["AdapterRAM"] == null) { this.lblMemoriaKartes.Text = mo["AdapterRAM"].ToString(); } else { this.lblMemoriaKartes.Text = formatSize(Int64.Parse(mo["AdapterRAM"].ToString()), false); } } } catch {} finally { this.label2.Visible = true; this.label8.Visible = true; this.label10.Visible = true; } }
//Returns an Object collection containing information about all the drives connected, and the storage status of them. public static ManagementObjectCollection DiskMetaData() { System.Management.ManagementScope managementScope = new System.Management.ManagementScope(); System.Management.ObjectQuery objectQuery = new System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3"); ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, objectQuery); ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get(); return(managementObjectCollection); }
public static List <Printer> GetAllPrinters() { List <Printer> printers = new List <Printer>(); System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection moc = mosearcher.Get(); if (moc != null && moc.Count > 0) { //For each printer found, we put it either in the local or network combobox, accordingly. foreach (ManagementObject mo in moc) { /*bool isLocal = true; * string[] ipAddress = mo["PortName"].ToString().Split('.'); * * //network printer * if (mo["PortName"] != null && ipAddress.Length == 4) * isLocal = false;*/ //get availability status printers.Add(new Printer { Prn_name = mo["Name"].ToString(), Pc_name = mo["SystemName"].ToString(), Status = mo.Properties["Availability"].Value == null ? "Не подключен" : mo.Properties["Availability"].Value.ToString(), Islocal = Convert.ToBoolean(mo.Properties["Local"].Value) }); #region SetDefaultPrinter //If the printer is found to be the default one, we select it. /* if ((bool)mo["Default"]) * { * if (network) * { * cboNetworkPrinters.SelectedItem = mo["Name"].ToString(); * defaultNetwork = true; * } * else * { * cboLocalPrinters.SelectedItem = mo["Name"].ToString(); * defaultNetwork = false; * } * * lblNameValue.Text = mo["Name"].ToString(); * lblPortValue.Text = mo["PortName"].ToString(); * lblDriverValue.Text = mo["DriverName"].ToString(); * lblDeviceIDValue.Text = mo["DeviceID"].ToString(); * lblSharedValue.Text = mo["Shared"].ToString(); * } */ #endregion } } return(printers); }
void mTestExecutionTimeoutTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { mTestExecutionTimeoutTimer.Enabled = false; if (mActiveExecution == null) { Window().logMessage("ERROR: received a execution timeout alert with no active execution."); return; } mActiveExecution.LogMessageWithTimeFromTrigger("ERROR: ABORTING EXECUTION DUE TO SEQUENCE TIMEOUT"); Window().logMessage("ERROR: Aborting execution of " + Name + " due to timeout"); //get Process objects System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("SELECT * FROM Win32_Process WHERE name='UVision.exe'"); ManagementObjectSearcher objSearcher = new ManagementObjectSearcher(oQuery); ManagementObjectCollection oReturnCollection = objSearcher.Get(); foreach (ManagementObject oReturn in oReturnCollection) {/* * //Name of process * Console.WriteLine(oReturn["Name"].ToString().ToLower()); * //arg to send with method invoke to return user and domain - below is link to SDK doc on it * string[] o = new String[2]; * //Invoke the method and populate the o var with the user name and domain * oReturn.InvokeMethod("GetOwner", (object[])o); * //write out user info that was returned * 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) * { * //get datetime string and convert * string s = oReturn["CreationDate"].ToString(); * //see ToDateTime function in sample code * DateTime dc = DateTime.Parse(s); * //write out creation date * Console.WriteLine("CreationDate: " + dc.AddTicks(-TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Ticks).ToLocalTime().ToString()); * } */ //this is the amount of memory used if (oReturn["WorkingSetSize"] != null) { long mem = Convert.ToInt64(oReturn["WorkingSetSize"].ToString()) / 1024; Window().logMessage("mem usage: " + mem); //Console.WriteLine("Mem Usage: {0:#,###.##}Kb", mem); } } mThread.Abort(); }
public SystemInfo() { ManagementObjectSearcher searcher; ObjectQuery query; uint i; os = "N/A"; cpu = "N/A"; mem = "N/A"; mobo = "N/A"; vga = "N/A"; sound = "N/A"; os = Environment.OSVersion.ToString(); ConnectionOptions conOptions = new ConnectionOptions(); ManagementScope scope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2", conOptions); query = new System.Management.ObjectQuery("SELECT * FROM Win32_Processor"); searcher = new ManagementObjectSearcher(scope, query); i = 0; foreach (ManagementObject item in searcher.Get()) { cpu = (i > 0 ? cpu + ", " : "") + item["Name"] + " @ " + Int64.Parse(item["MaxClockSpeed"].ToString()) + " MHz"; i++; } query = new System.Management.ObjectQuery("SELECT * FROM Win32_ComputerSystem"); searcher = new ManagementObjectSearcher(scope, query); i = 0; foreach (ManagementObject item in searcher.Get()) { mobo = (i > 0 ? mobo + ", " : "") + item["model"] + " (" + item["Manufacturer"] + ")"; mem = (i > 0 ? mem + ", " : "") + (uint)System.Math.Ceiling(Double.Parse(item["totalphysicalmemory"].ToString()) / 1048576.0) + " MB"; i++; } query = new System.Management.ObjectQuery("SELECT * FROM Win32_VideoController"); searcher = new ManagementObjectSearcher(scope, query); i = 0; foreach (ManagementObject item in searcher.Get()) { vga = (i > 0 ? vga + ", " : "") + item["Caption"]; i++; } query = new System.Management.ObjectQuery("SELECT * FROM Win32_SoundDevice"); searcher = new ManagementObjectSearcher(scope, query); i = 0; foreach (ManagementObject item in searcher.Get()) { sound = (i > 0 ? sound + ", " : "") + item["Caption"]; i++; } }
static void Main(string[] args) { ManagementScope ms = new System.Management.ManagementScope( @"\\myserver\root\cimv2"); var oq = new System.Management.ObjectQuery( "SELECT * FROM Win32_Process where Name='myprocname'"); ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms, oq); ManagementObjectCollection procsCollection = query1.Get(); Console.WriteLine("process count:{0}", procsCollection.Count); }
// Name processor public static string GetName() { string Proc = null; ObjectQuery win32ProcQuery = new System.Management.ObjectQuery("SELECT Name from Win32_Processor"); using (ManagementObjectSearcher win32Proc = new ManagementObjectSearcher(win32ProcQuery)) { var obj = win32Proc.Get().OfType <ManagementObject>().First(); Proc = obj["Name"].ToString(); } return(Proc); }