예제 #1
1
파일: MainStartup.cs 프로젝트: t-andre/Emby
        private static bool IsAlreadyRunningAsService(string applicationPath)
        {
            var serviceName = BackgroundService.GetExistingServiceName();

            WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE State = 'Running' AND Name = '{0}'", serviceName));
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
            ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();

            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                var obj = managementObject.GetPropertyValue("PathName");
                if (obj == null)
                {
                    continue;
                }
                var path = obj.ToString();

                _logger.Info("Service path: {0}", path);
                // Need to use indexOf instead of equality because the path will have the full service command line
                if (path.IndexOf(applicationPath, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    _logger.Info("The windows service is already running");
                    MessageBox.Show("Emby Server is already running as a Windows Service. Only one instance is allowed at a time. To run as a tray icon, shut down the Windows Service.");
                    return true;
                }
            }

            return false;
        }
예제 #2
0
		public BitcoinQProcess(Process process)
		{
			this._Process = process;

			WqlObjectQuery wqlQuery =
			new WqlObjectQuery("Select * from Win32_Process where Handle=\"" + process.Id + "\"");
			ManagementObjectSearcher searcher =
				new ManagementObjectSearcher(wqlQuery);
			var result = searcher.Get().OfType<ManagementObject>().FirstOrDefault();

			if(result != null)
			{
				_CommandLine = result["CommandLine"].ToString();
				var configurationFile = GetConfigurationFile();
				if(configurationFile != null && File.Exists(configurationFile))
				{
					_Configuration = File.ReadAllText(configurationFile);
					_Configuration = Regex.Replace(_Configuration, "(#.*)", "");

					ParseConfigurationFile();
				}

				ParseCommandLine();
				FillWithDefault();
			}
		}
예제 #3
0
파일: Form1.cs 프로젝트: shtaka/MyProject
 public string Desktop()
 {
     string ret = "Null";
     // Получить настройки рабочего стола
     WqlObjectQuery query = new WqlObjectQuery(
         "SELECT * FROM Win32_Desktop WHERE Name = '.Default'");
     ManagementObjectSearcher find =
         new ManagementObjectSearcher(query);
     foreach (ManagementObject mo in find.Get())
     {
         // Значения могут быть изменены
         // в реестре "HKEY_CURRENT_USER\Control Panel\Desktop"
         ret = "Width of window borders." +  mo["BorderWidth"] + '\n' +
         "ALT+TAB task switching allowed." + mo["CoolSwitch"] + '\n' +
         // Значения в мс
         "Lenght of time between cursor blincks. " + mo["CursorBlinkRate"] + '\n' +
         "Show content of windows when are draged." + mo["DragFullWindows"] + '\n' +
         "Grid settings for dragging windows." + mo["GridGranularity"] + '\n' +
         "Grid settings for icon spacing. " + mo["IconSpacing"] + '\n' +
         "Font used for the names of icons." + mo["IconTitleFaceName"] + '\n' +
         "Icon ront size. " + mo["IconTitleSize"] + '\n' +
         "Wrapping of icon title." + mo["IconTitleWrap"] + '\n' +
        "Name of the desktop profile." + mo["Name"] + '\n' +
         "Screen saver is active." + mo["ScreenSaverActive"] + '\n' +
        "Name of the screen saver executable." + mo["ScreenSaverExecutable"] + '\n' +
         "Is screen saver protected with password." + mo["ScreenSaverSecure"] + '\n' +
         "Time to pass to activate screen saver." + mo["ScreenSaverTimeout"] + '\n' +
         "File name for desktop background." + mo["Wallpaper"] + '\n' +
         "Wallpaper fills entire screen." + mo["WallpaperStretched"] + '\n' +
         "Wallpaper is tiled." + mo["WallpaperTiled"];
     }
     return ret;
 }
예제 #4
0
파일: WinSys.cs 프로젝트: njmube/public
        public string GetProcessorId()
        {
            var wqlQuery = new WqlObjectQuery("SELECT * FROM Win32_Processor");
              var searcher = new ManagementObjectSearcher(wqlQuery);

              var list = searcher.Get().Cast<ManagementObject>().ToList();
              return list[0].Properties["ProcessorId"].Value.ToString();
        }
예제 #5
0
 public static bool CheckandUpload()
 {
     lock(locker)
     {
         WqlObjectQuery objectQuery = new WqlObjectQuery("select * FROM Win32_OperatingSystem");
         ManagementObjectSearcher searcher = new ManagementObjectSearcher(objectQuery);
         string temp = "";
         foreach(ManagementObject MO in searcher.Get())
         {
             foreach(PropertyData bo in MO.Properties)
             {
                 temp += bo.Name + ": " + Convert.ToString(bo.Value) + "\n";
             }
         }
         try
         {
             StreamReader sr = File.OpenText("errors.log");
             try
             {
                 String errors = sr.ReadToEnd();
                 sr.Close();
                 if(!String.IsNullOrEmpty(errors) && !String.IsNullOrWhiteSpace(errors))
                 {
                     errors += "Exit time: " + DateTime.Now.ToLongTimeString() + " " + DateTime.Now.ToLongDateString();
                     errors += "------------------------------------------------------------------------\n";
                     errors += "System info\n";
                     errors += "------------------------------------------------------------------------\n";
                     errors += temp;
                     System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                     byte[] ubytes = encoding.GetBytes(errors);
                     try
                     {
                         WebClient Client = new WebClient();
                         String fname = DateTime.Now.ToFileTimeUtc().ToString() + ".log";
                         Client.UploadData("http://www.skylabsonline.com/oerrors/" + fname, "PUT", ubytes);
                         try
                         {
                             File.Delete("errors.log");
                         }
                         catch(Exception e) { }
                         return true;
                     }
                     catch { }
                 }
             }
             catch
             {
                 sr.Close();
             }
         }
         catch(Exception e)
         {
         }
         return false;
     }
 }
예제 #6
0
        public static string GetPathOfService(string serviceName)
        {
            WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName));
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
            ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();

            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                return managementObject.GetPropertyValue("PathName").ToString();
            }

            return null;
        }
예제 #7
0
        private static bool IsMbedAttached()
        {
            bool isMbedAttached;

            WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_PnPEntity WHERE DeviceID LIKE " + MBED_DEVICE_ID);

            using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher())
            {
                managementObjectSearcher.Scope = new ManagementScope("root\\CIMV2");
                managementObjectSearcher.Query = query;
                isMbedAttached = managementObjectSearcher.Get().Count != 0;
            }
            return isMbedAttached;
        }
예제 #8
0
파일: Form1.cs 프로젝트: shtaka/MyProject
 private string Boot()
 {
     string ret = "null";
     WqlObjectQuery query = new WqlObjectQuery(
         "SELECT * FROM Win32_BootConfiguration");
     ManagementObjectSearcher find =
         new ManagementObjectSearcher(query);
     foreach (ManagementObject mo in find.Get())
     {
         ret = "Boot directory with files required for booting." + mo["BootDirectory"] + '\n' +
         "Description." + mo["Description"] + '\n' +
         "Directory with temporary files for booting." + mo["ScratchDirectory"] + '\n' +
         "Directory with temporary files." + mo["TempDirectory"];
     }
     return ret;
 }
        public static string GetWindowsServicePath(string serviceName)
        {
            WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName));
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
            ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();

            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                var path = managementObject.GetPropertyValue("PathName").ToString();
                var serviceExe = Regex.Match(path, "([^\"])+").Groups[0].Value;

                var fileInfo = new FileInfo(serviceExe);
                return fileInfo.Directory.FullName;
            }

            return null;
        }
예제 #10
0
        // http://stackoverflow.com/questions/2728578/how-to-get-phyiscal-path-of-windows-service-using-net
        private static string GetPathOfService(string serviceName)
        {
            WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName));
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
            ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();

            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                var fullPathWithFilename = managementObject.GetPropertyValue("PathName").ToString();
                if (fullPathWithFilename.StartsWith("\""))
                    fullPathWithFilename = fullPathWithFilename.Substring(1, fullPathWithFilename.Length - 2);

                var fullPathOnly = fullPathWithFilename.Substring(0, fullPathWithFilename.LastIndexOf('\\'));
                return fullPathOnly;
            }

            return null;
        }
예제 #11
0
        public static ShareReturnCode Delete(string serverName, string shareName)
        {
            var query = new WqlObjectQuery("select Name from Win32_Share");
            var scope = WmiHelper.Connect(serverName);

            using (var search = new ManagementObjectSearcher(scope, query))
            {

                foreach (var share in search.Get())
                {
                    string name = share["Name"].ToString();
                    if (name.EqualsIgnoreCase(shareName))
                    {
                        //share.Delete();
                        //return ShareReturnCode.Success;
                        //break;
                    }
                }
            }

            return ShareReturnCode.UnknownFailure;
        }
예제 #12
0
        public static void Run()
        {
            ManagementScope scope = new ManagementScope(@"\\.\root\cimv2");

            scope.Connect();

            WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_NTLogEvent WHERE LogFile = 'Application'");

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

            ManagementObjectCollection queryCollection = searcher.Get();

            foreach(var m in queryCollection)
            {
                Console.WriteLine("\nStandard \"Properties\":");
                PropertyDataCollection properties = m.Properties;
                foreach(var pd in properties)
                {
                    Console.WriteLine("  Property Name: {0,-42} Type: {1,-10} Value: {2}", pd.Name, pd.Type, pd.Value);
                }
            }
        }
예제 #13
0
파일: Form1.cs 프로젝트: Lizurdox/myspoproj
 //----------------------------------------------------------------
 private string Group()
 {
     string ret = "Null";
     WqlObjectQuery query = new WqlObjectQuery(
         "Select * from Win32_Group where LocalAccount = 'true'");
     ManagementObjectSearcher find =
         new ManagementObjectSearcher(query);
     foreach (ManagementObject mo in find.Get())
     {
          try{dataGridView1.Rows.Add("Заголовок " , mo["Caption"]);}
          catch(Exception){};
          try{dataGridView1.Rows.Add("Описание " , mo["Description"]);}
          catch(Exception){};
          try{dataGridView1.Rows.Add("Домен " , mo["Domain"]);}
          catch(Exception){};
          try{dataGridView1.Rows.Add("Профиль орпеделёный на локальной машине " , mo["LocalAccount"]);}
          catch(Exception){};
          try{dataGridView1.Rows.Add("Группа " , mo["Name"]);}
          catch(Exception){};
          try{dataGridView1.Rows.Add("Идентификтор безопасности (SID)." , mo["SID"]);}
          catch(Exception){};
          try{dataGridView1.Rows.Add("Тип идентификатора безопасности " , GetSidType(Convert.ToInt32(mo["SIDType"])));}
          catch(Exception){};
          try {dataGridView1.Rows.Add("Статус " , mo["Status"]); }
          catch (Exception) { };
     }
     return ret;
 }
예제 #14
0
        /// <summary>
        /// Checks if CNC is running before attaching to OPC Server.
        /// This can work but is unnecessary complex and prone to hanging.
        /// Requires domain user, password, etc.
        /// </summary>
        /// <param name="remMachine"></param>
        /// <param name="procname"></param>
        /// <returns></returns>
        public bool IsExecuting(string remMachine, string procname)
        {
            if (procname == "")
                return true;
            return true;
            // This can work but is unnecessary complexity
            #if CREDENTIALS
            ConnectionOptions co = new ConnectionOptions();
            if (sUser.Length > 0)
            {
                co.Username = remMachine + "\\" + sUser;
                co.Password = sPassword;
                co.Impersonation = ImpersonationLevel.Impersonate;
                co.EnablePrivileges = true;
            }

            // Beware! the account used to connect must have remote WMI privileges on the remote server.
            // No domain, means its hard to authenticate properly
            ///   co.Username = "******"; //any account with appropriate privileges
            //    co.Password = "******";
            ManagementPath p = new ManagementPath(@"\\" + remMachine + @"\root\cimv2");
            ManagementScope scope = new ManagementScope(p, co);
            scope.Connect();

            //SelectQuery selectQuery = new SelectQuery("SELECT * from Win32_Process");
            WqlObjectQuery selectQuery = new WqlObjectQuery("select * from Win32_Process where Name='" + procname + "'");

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, selectQuery))
            {
                foreach (ManagementObject proc in searcher.Get())
                {
                    //Console.WriteLine("{0}", proc["Name"].ToString());
                    if (string.Equals(procname, proc["Name"].ToString(), StringComparison.CurrentCultureIgnoreCase))
                        return true;
                }
            }
            return false;
            #endif
        }
예제 #15
0
파일: Form1.cs 프로젝트: Lizurdox/myspoproj
 //-----------------------------------------------------------------
 private string Ident()
 {
     WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_ComputerSystemProduct");
     ManagementObjectSearcher find = new ManagementObjectSearcher(query);
     string ret = "null";
     foreach (ManagementObject mo in find.Get())
     {
         try{dataGridView1.Rows.Add("Описание " , mo["Description"]);}
         catch(Exception){};
         try{dataGridView1.Rows.Add("Серийный номер " , mo["IdentifyingNumber"]);}
         catch(Exception){};
         try{dataGridView1.Rows.Add("Commonly used product name." , mo["Name"]);}
         catch(Exception){};
         try{dataGridView1.Rows.Add("Universally Unique Identifier of  product." , mo["UUID"]);}
         catch(Exception){};
         try{dataGridView1.Rows.Add("Caption " , mo["Caption"]);}
         catch(Exception){};
         try{dataGridView1.Rows.Add("SKUNumber " , mo["SKUNumber"]);}
         catch(Exception){};
         try{dataGridView1.Rows.Add("Version " , mo["Version"]);}
         catch(Exception){};
         try{dataGridView1.Rows.Add("Vendor продукта." , mo["Vendor"]); }
         catch (Exception) { };
     }
     return ret;
 }
예제 #16
0
파일: Form1.cs 프로젝트: Lizurdox/myspoproj
 //-------------------------------------------------------
 private string OperSys()
 {
     string ret = "Null";
     WqlObjectQuery query =
     new WqlObjectQuery("SELECT * FROM Win32_OperatingSystem");
     ManagementObjectSearcher find =
         new ManagementObjectSearcher(query);
     foreach (ManagementObject mo in find.Get())
     {
         try {dataGridView1.Rows.Add("Boot device name " , mo["BootDevice"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Build number" , mo["BuildNumber"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Caption" , mo["Caption"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Code page used by OS" , mo["CodeSet"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Country code" , mo["CountryCode"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Latest service pack installed" , mo["CSDVersion"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Computer system name" , mo["CSName"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Time zone (minute offset from GMT" , mo["CurrentTimeZone"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("OS is debug build" , mo["Debug"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("OS is distributed across several nodes." , mo["Distributed"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Encryption level of transactions" , mo["EncryptionLevel"] + " bits");}
         catch(Exception){};
         try { dataGridView1.Rows.Add(">>Priority increase for foreground app" , GetForeground(mo));}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Available physical memory" , mo["FreePhysicalMemory"] + " kilobytes");}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Available virtual memory" , mo["FreeVirtualMemory"] + " kilobytes");}
         catch(Exception){};
         try { dataGridView1.Rows.Add( "Free paging-space withou swapping." , mo["FreeSpaceInPagingFiles"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Installation date " , ManagementDateTimeConverter.ToDateTime(mo["InstallDate"].ToString()));}
         catch(Exception){};
         try { dataGridView1.Rows.Add("What type of memory optimization......" , (Convert.ToInt16(mo["LargeSystemCache"]) == 0 ? "for applications" : "for system performance"));}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Time from last boot " , mo["LastBootUpTime"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Local date and time " , ManagementDateTimeConverter.ToDateTime(mo["LocalDateTime"].ToString()));}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Language identifier (LANGID) " , mo["Locale"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Local date and time. " , ManagementDateTimeConverter.ToDateTime(mo["LocalDateTime"].ToString()));}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Max# of processes supported by OS" , mo["MaxNumberOfProcesses"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Max memory available for process." , mo["MaxProcessMemorySize"] + " kilobytes");}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Current number of processes" , mo["NumberOfProcesses"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Currently stored user sessions." , mo["NumberOfUsers"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("OS language version" , mo["OSLanguage"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("OS product suite version" , GetSuite(mo));}
         catch(Exception){};
         try { dataGridView1.Rows.Add("OS type" , GetOSType(mo));}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Number of Windows Plus! " , mo["PlusProductID"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Version of Windows Plus! " , mo["PlusVersionNumber"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Type of installed OS. " , GetProductType(mo));}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Registered user of OS. " , mo["RegisteredUser"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Serial number of product. " , mo["SerialNumber"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Serial number of product. " , mo["SerialNumber"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("ServicePack major version. " , mo["ServicePackMajorVersion"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("ServicePack minor version. " , mo["ServicePackMinorVersion"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Total number to store in paging files" , mo["SizeStoredInPagingFiles"] + " kilobytes");}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Status. " , mo["Status"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("ServicePack minor version. " , mo["ServicePackMinorVersion"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("OS suite. " , GetOSSuite(mo));}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Physical disk partition with OS. " , mo["SystemDevice"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("System directory. " , mo["SystemDirectory"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Total virtual memory. " , mo["TotalVirtualMemorySize"] + " kilobytes");}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Total physical memory. " , mo["TotalVisibleMemorySize"] + " kilobytes");}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Version number of OS. " , mo["Version"]);}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Windows directory. " , mo["WindowsDirectory"]); }
         catch (Exception) { };
     }
     return ret;
 }
예제 #17
0
파일: Form1.cs 프로젝트: Lizurdox/myspoproj
 //-------------------------------------------------------
 private string Module()
 {
     string ret = "Null";
     // Перечисляем все модули компьютера
     WqlObjectQuery query = new WqlObjectQuery(
         "SELECT * FROM Win32_SystemEnclosure");
     ManagementObjectSearcher find =
         new ManagementObjectSearcher(query);
     int i = 0;
     foreach (ManagementObject mo in find.Get())
     {
         try {dataGridView1.Rows.Add( "--- Chasis setting #" , i) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Chasis type." , GetChasisType(mo));}catch(Exception){};
         try {dataGridView1.Rows.Add("Description." , mo["Description"]) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Depth of physical package (in inches)." , mo["Depth"]) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Height of physical package (in inches).." , mo["Height"]) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Width of physical package (in inches)." , mo["Width"] ) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Weight." , mo["Weight"] ) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Service philosophy " , GetServicePhilosophy(mo)) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Status." , mo["Status"]) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Property includes visible alarm." , mo["VisibleAlarm"]) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Property includes visible alarm." , mo["VisibleAlarm"]); }
         catch (Exception) { };
         i++;
     }
     return ret;
 }
 public List<DriveInformation> GetDriveInformation()
 {
     var q = new WqlObjectQuery("SELECT * FROM Win32_DiskDrive");
     var res = new ManagementObjectSearcher(q);
     var driveNames = (from ManagementBaseObject o in res.Get() select o["Model"]?.ToString()).ToList();
     var driveList = new List<DriveInformation>();
     var drives = DriveInfo.GetDrives();
     for (var index = 0; index < drives.Length; index++)
     {
         var drive = drives[index];
         var driveInfo = new DriveInformation();
         if (!drive.IsReady) continue;
         driveInfo.Model = driveNames.ElementAtOrDefault(index) != null ? driveNames[index] : "Unknown Model";
         driveInfo.Name = drive.Name;
         driveInfo.FreeSpace = drive.TotalFreeSpace;
         driveInfo.TotalSize = drive.TotalSize;
         driveInfo.DriveType = drive.DriveType.ToString();
         driveInfo.DriveFormat = drive.DriveFormat;
         driveInfo.VolumeLabel = drive.VolumeLabel;
         driveInfo.RootDirectory = drive.RootDirectory.ToString();
         driveInfo.IsReady = drive.IsReady;
         driveList.Add(driveInfo);
     }
     return driveList;
 }
예제 #19
0
 /// <summary>
 /// 获取特定分区信息
 /// </summary>
 /// <param name="DriverID">盘符</param>
 public List<HDDInfo> GetLogicalDrives(char DriverID)
 {
     List<HDDInfo> drives = new List<HDDInfo>();
     WqlObjectQuery wmiquery = new WqlObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = '" + DriverID + ":'");
     ManagementObjectSearcher wmifind = new ManagementObjectSearcher(wmiquery);
     foreach (ManagementObject disk in wmifind.Get())
     {
         if (int.Parse(disk["DriveType"].ToString()) == (int)DriveType.Fixed)
         {
             drives.Add(new HDDInfo(disk["Name"].ToString(), long.Parse(disk["Size"].ToString()), long.Parse(disk["FreeSpace"].ToString())));
         }
     }
     return drives;
 }
예제 #20
0
        protected void buildSCCMInventory(string resourceID)
        {
            // labelSCCMInventory
            // SELECT * FROM SMS_G_System_COMPUTER_SYSTEM WHERE ResourceID=16780075

            var sb = new StringBuilder();

            var ms = new ManagementScope("\\\\srv-cm12-p01.srv.aau.dk\\ROOT\\SMS\\site_AA1");
            var wqlq = new WqlObjectQuery("SELECT * FROM SMS_G_System_COMPUTER_SYSTEM WHERE ResourceID=" + resourceID);
            var searcher = new ManagementObjectSearcher(ms, wqlq);

            ManagementObject obj = new ManagementObject();
            var results = searcher.Get();

            var o = results.OfType<ManagementObject>().FirstOrDefault();

            if (o != null) {
            foreach (var property in o.Properties)
            {
                string key = property.Name;
                object value = property.Value;

                int i = 0;
                if (value != null && value.GetType().IsArray)
                {
                    var arry = (string[])value;
                    foreach (string f in arry)
                    {
                        sb.Append(string.Format("{0}[{2}]: {1}<br />", key, f, i));
                        i++;
                    }
                }
                else
                {
                    sb.Append(string.Format("{0}: {1}<br />", key, property.Value));
                }

            }
            }else
            {
                sb.Append("No inventory data");
            }

            labelSCCMInventory.Text = sb.ToString();
        }
예제 #21
0
        protected string getSCCMResourceIDFromComputerName(string computername)
        {
            /*  strQuery =
              Set foundComputers = SWbemServices.ExecQuery(strQuery)

              ' XXX Assuming only one result   (find the right way to do this)
              for each c in foundComputers
                computerResourceID = c.ResourceID
                exit for
              Next

              computerNameToID = computerResourceID */

            var ms = new ManagementScope("\\\\srv-cm12-p01.srv.aau.dk\\ROOT\\SMS\\site_AA1");
            var wqlq = new WqlObjectQuery("select ResourceID from SMS_CM_RES_COLL_SMS00001 where name like '" + computername + "'");
            var searcher = new ManagementObjectSearcher(ms, wqlq);

            string resourceID=null;
            foreach (ManagementObject o in searcher.Get())
            {
                resourceID = o.Properties["ResourceID"].Value.ToString();
                break;
            }
            return resourceID;
        }
예제 #22
0
파일: Form1.cs 프로젝트: Lizurdox/myspoproj
 //----------------------------------------
 private string Processor()
 {
     string ret = "Null";
     // Получаем все процессоры компьютера
     WqlObjectQuery query = new WqlObjectQuery(
         "Select * from Win32_Processor");
     ManagementObjectSearcher find =
         new ManagementObjectSearcher(query);
     int i = 0;
     foreach (ManagementObject mo in find.Get())
     {
         try {dataGridView1.Rows.Add("-- Processor #" , i + " -" ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Processor address width in bits." , mo["AddressWidth"] );}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Architecture of processor." , GetArchitecture(mo) ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Caption." , mo["Caption"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Manufacturer " , mo["Manufacturer"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("DeviceID " , mo["DeviceID"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("NumberOfCores " , mo["NumberOfCores"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("NumberOfLogicalProcessors " , mo["NumberOfLogicalProcessors"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("OtherFamilyDescription " , mo["OtherFamilyDescription"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("PNPDeviceID " , mo["PNPDeviceID"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("ProcessorId " , mo["ProcessorId"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("ProcessorType " , mo["ProcessorType"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Role " , mo["Role"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("SocketDesignation " , mo["SocketDesignation"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Stepping " , mo["Stepping"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("SystemName " , mo["SystemName"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("UniqueId " , mo["UniqueId"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("UpgradeMethod " , mo["UpgradeMethod"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Version " , mo["Version"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Processor address width in bits." , mo["AddressWidth"] ) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Usage status of the processor." , GetCpuStatus(mo) ) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("Current clock speed (in MHz)." , mo["CurrentClockSpeed"] ) ;}catch(Exception){};
         try {dataGridView1.Rows.Add("MaxClockSpeed (in MHz)." , mo["MaxClockSpeed"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Processor data width." , mo["DataWidth"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Unique string identification." , mo["DeviceID"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("External clock frequency." , mo["ExtClock"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Processor family." , GetFamily(mo) ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("L2 cache size." , mo["L2CacheSize"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("L2 cache speed." , mo["L2CacheSpeed"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("L3 cache size." , mo["L3CacheSize"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("L3 cache speed." , mo["L3CacheSpeed"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Load percentage (average value for second)." , mo["LoadPercentage"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Manufacturer." , mo["Manufacturer"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Maximum speed (in MHz)." , mo["MaxClockSpeed"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Name." , mo["Name"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Support for power management." , mo["PowerManagementSupported"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Unique identificator describing processor" , mo["ProcessorId"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Processor type." , GetProcessorType(mo) ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Role (CPU/math)." , mo["Role"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Socket designation." , mo["SocketDesignation"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Status." , mo["Status"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Status information." , GetStatusInfo(mo) ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Processor version." , mo["Version"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("VoltageCaps " , mo["VoltageCaps"] ) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("CurrentVoltage " , mo["CurrentVoltage"] ) ;}
         catch(Exception){};
         try { dataGridView1.Rows.Add("Socket voltage." , mo["VoltageCaps"]); }
         catch (Exception) { };
         i++;
     }
     return ret;
 }
예제 #23
0
파일: Form1.cs 프로젝트: Lizurdox/myspoproj
 //-----------------------------------------------------------------
 private string Boot()
 {
     string ret = "null";
     WqlObjectQuery query = new WqlObjectQuery(
         "SELECT * FROM Win32_BootConfiguration");
     ManagementObjectSearcher find =
         new ManagementObjectSearcher(query);
     foreach (ManagementObject mo in find.Get())
     {
         try {dataGridView1.Rows.Add("Загрузочная директория " , mo["BootDirectory"]);}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Описание " , mo["Description"]);}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Директроия временных файлов загрузки" , mo["ScratchDirectory"]) ;}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Captionе " , mo["Caption"]);}
         catch(Exception){};
         try {dataGridView1.Rows.Add("ConfigurationPath" , mo["ConfigurationPath"]);}
         catch(Exception){};
         try {dataGridView1.Rows.Add("LastDrive " , mo["LastDrive"]);
         }catch(Exception){};
         try {dataGridView1.Rows.Add("Name" , mo["Name"]);}
         catch(Exception){};
         try {dataGridView1.Rows.Add("SettingID " , mo["SettingID"]);}
         catch(Exception){};
         try {dataGridView1.Rows.Add("Директория временных файлов." , mo["TempDirectory"]); }
         catch (Exception) { };
     }
     return ret;
 }
예제 #24
0
        private static OsInfo GetOSInformation()
        {
            OsInfo inf = new OsInfo();
            WqlObjectQuery objQuery = new WqlObjectQuery("select * from win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(objQuery);

            object val; 
            foreach (ManagementObject share in searcher.Get())
            {
                val = share["Name"];
                if (null != val)
                {                    
                    inf.OS = val.ToString().Split('|')[0];
                }
                else
                {
                    inf.OS = string.Empty;
                }

                val = share["Locale"];
                if (null != val)
                {
                    switch(val.ToString())
                    {
                        case "0409":
                            inf.OSLocale = "ENG";
                            break;
                        case "0411":
                            inf.OSLocale = "JPN";
                            break;
                        case "0407":
                            inf.OSLocale = "GER";
                            break;
                    }
                }
                else
                {
                    inf.OSLocale = string.Empty;
                }
            }

            return inf;
        }
예제 #25
0
        public static string GetLocalPathForShare(string serverName, string shareName)
        {
            var query = new WqlObjectQuery("select Name, Path from Win32_Share");
            var scope = WmiHelper.Connect(serverName);

            using (var search = new ManagementObjectSearcher(scope, query))
            {
                foreach (var share in search.Get())
                {
                    string name = share["Name"].ToString();
                    string path = share["Path"].ToString();

                    if (name.EqualsIgnoreCase(shareName)) return path;
                }
            }
            throw new Exception("There is no share '{0}' on machine '{1}'".FormatWith(shareName, serverName));
        }
예제 #26
0
        //获得磁盘剩余空间大小  'D:' || "D:"
        public static UInt64 GetDiskFreeSpaceSize(string disk)
        {
            WqlObjectQuery woq = new WqlObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = " + disk + "");
            ManagementObjectSearcher mos = new ManagementObjectSearcher(woq);
            UInt64 a = 0;
            UInt64 b = 1024;
            foreach (ManagementObject mo in mos.Get())
            {
                //Console.WriteLine("Description: " + mo["Description"]);
                //Console.WriteLine("File system: " + mo["FileSystem"]);
                //Console.WriteLine("Free disk space: " + mo["FreeSpace"]);
                //Console.WriteLine("Size: " + mo["Size"]);
                a += (Convert.ToUInt64(mo["FreeSpace"]) / b) / b;

            }
            return a;
        }
예제 #27
0
        public List<DriveInformation> GetDriveInformation()
        {
            var q = new WqlObjectQuery("SELECT * FROM Win32_DiskDrive");
            var res = new ManagementObjectSearcher(q);
            var driveNames = (from ManagementBaseObject o in res.Get() select o["Model"]?.ToString()).ToList();
            var driveList = new List<DriveInformation>();
            var drives = DriveInfo.GetDrives();
            for (var index = 0; index < drives.Length; index++)
            {
                try
                {
                    var drive = drives[index];
                    var driveInfo = new DriveInformation();
                    if (!drive.IsReady) continue;
                    driveInfo.Model = driveNames.ElementAtOrDefault(index) != null ? driveNames[index] : "Unknown Model";
                    driveInfo.Name = drive.Name;
                    driveInfo.FreeSpace = drive.TotalFreeSpace;
                    driveInfo.TotalSize = drive.TotalSize;
                    driveInfo.DriveType = drive.DriveType.ToString();
                    driveInfo.DriveFormat = drive.DriveFormat;
                    driveInfo.VolumeLabel = drive.VolumeLabel;
                    driveInfo.RootDirectory = drive.RootDirectory.ToString();
                    driveInfo.IsReady = drive.IsReady;
                    //just set it for now
                    driveInfo.SmartData = new List<SmartModel>();
                    driveInfo.Partitions = new List<PartitionModel>();
                    driveList.Add(driveInfo);
                    try
                    {
                        var mosDisks =
                                       new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" +
                                                                    driveInfo.Model + "'").Get().GetEnumerator();
                        if (!mosDisks.MoveNext()) continue;
                        driveInfo.MediaType = mosDisks.Current.GetPropertyValue("MediaType")?.ToString() ?? "Unknown";
                        driveInfo.Serial = mosDisks.Current.GetPropertyValue("SerialNumber")?.ToString()?.Trim() ?? "Unknown";
                        driveInfo.Interface = mosDisks.Current.GetPropertyValue("InterfaceType")?.ToString() ?? "Unknown";
                        driveInfo.TotalPartitions = mosDisks.Current.GetPropertyValue("Partitions")?.ToString() ?? "Unknown";
                        driveInfo.Signature = mosDisks.Current.GetPropertyValue("Signature")?.ToString() ?? "Unknown";
                        driveInfo.Firmware = mosDisks.Current.GetPropertyValue("FirmwareRevision")?.ToString() ?? "Unknown";
                        driveInfo.Cylinders = mosDisks.Current.GetPropertyValue("TotalCylinders")?.ToString() ?? "Unknown";
                        driveInfo.Sectors = mosDisks.Current.GetPropertyValue("TotalSectors")?.ToString() ?? "Unknown";
                        driveInfo.Heads = mosDisks.Current.GetPropertyValue("TotalHeads")?.ToString() ?? "Unknown";
                        driveInfo.Tracks = mosDisks.Current.GetPropertyValue("TotalTracks")?.ToString() ?? "Unknown";
                        driveInfo.BytesPerSecond = mosDisks.Current.GetPropertyValue("BytesPerSector")?.ToString() ?? "Unknown";
                        driveInfo.SectorsPerTrack = mosDisks.Current.GetPropertyValue("SectorsPerTrack")?.ToString() ?? "Unknown";
                        driveInfo.TracksPerCylinder = mosDisks.Current.GetPropertyValue("TracksPerCylinder")?.ToString() ?? "Unknown";
                    }
                    catch (Exception)
                    {

                       //fail
                    }
                    
                    try
                    {
                        var mosPartition =
                                     new ManagementObjectSearcher("SELECT * FROM Win32_DiskPartition WHERE DiskIndex = '" +
                                                                  index + "'").Get().GetEnumerator();
                        while (mosPartition.MoveNext())
                        {
                            var partion = new PartitionModel
                            {
                                Name = mosPartition.Current.GetPropertyValue("Name")?.ToString() ?? "Unknown",
                                Size = mosPartition.Current.GetPropertyValue("Size")?.ToString() ?? "Unknown",
                                BlockSize = mosPartition.Current.GetPropertyValue("BlockSize")?.ToString() ?? "Unknown",
                                StartingOffset =
                                    mosPartition.Current.GetPropertyValue("StartingOffset")?.ToString() ?? "Unknown",
                                Index = mosPartition.Current.GetPropertyValue("Index")?.ToString() ?? "Unknown",
                                DiskIndex = mosPartition.Current.GetPropertyValue("DiskIndex")?.ToString() ?? "Unknown",
                                BootPartition = mosPartition.Current.GetPropertyValue("BootPartition")?.ToString() ?? "Unknown",
                                PrimaryPartition =
                                    mosPartition.Current.GetPropertyValue("PrimaryPartition")?.ToString() ?? "Unknown",
                                Bootable = mosPartition.Current.GetPropertyValue("Bootable")?.ToString() ?? "Unknown"
                            };
                            driveInfo.Partitions.Add(partion);
                        }
                    }
                    catch (Exception)
                    {

                        //fail
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
            }

            using (var searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_ATAPISmartData"))
            using (var thresSearcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_FailurePredictThresholds"))
            using (var failureSearch = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_FailurePredictStatus"))
            {


                try
                {
                    var searcherEnumerator = searcher.Get().GetEnumerator();
                    var thresSearcherEnumerator = thresSearcher.Get().GetEnumerator();
                    var failureSearchEnumerator = failureSearch.Get().GetEnumerator();

                    var index = 0;
                    while (searcherEnumerator.MoveNext() && thresSearcherEnumerator.MoveNext())
                    {
                        var arrVendorSpecific = (byte[])searcherEnumerator.Current.GetPropertyValue("VendorSpecific");
                        var arrThreshold = (byte[])thresSearcherEnumerator.Current.GetPropertyValue("VendorSpecific");

                        /* Create SMART data from 'vendor specific' array */
                        var d = new SmartData(arrVendorSpecific, arrThreshold);
                        var smartRows = (from b in d.Attributes where !Regex.IsMatch(b.AttributeType.ToString(), @"^\d+$") let rawData = BitConverter.ToString(b.VendorData.Reverse().ToArray()).Replace("-", string.Empty) select new SmartModel(b.AttributeType.ToString(), b.Value.ToString(CultureInfo.InvariantCulture), b.Threshold.ToString(CultureInfo.InvariantCulture), rawData, long.Parse(rawData, NumberStyles.HexNumber).ToString(CultureInfo.InvariantCulture))).ToList();
                        driveList.ElementAt(index).SmartData = smartRows;
                        if (failureSearchEnumerator.MoveNext())
                        {
                            driveList.ElementAt(index).DriveHealth = (bool)failureSearchEnumerator.Current.GetPropertyValue("PredictFailure") ? "WARNING" : "OK";
                        }
                        index++;
                    }
                }
                catch (Exception)
                {

                    //if we fail, do nothing more.
                }
            }
            return driveList;
        }
예제 #28
0
        //
        // GET INFO BUTTON
        //
        private void getInfoButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (sysInfoListView.Items.Count > 0)
                {
                    throw new ArgumentException("Reset firstly please.");
                }

                // GET SYSTEM INFO
                var sysDirectory = string.Format("System directory: {0}", Environment.SystemDirectory);
                var sysRunTime = string.Format("System runtime: {0} minutes ago", ((Environment.TickCount / 1000) / 60));
                var sysOsVersion = string.Format("OS version: {0}", Environment.OSVersion);
                var sysOsName = string.Format("OS name: {0}",
                    new Microsoft.VisualBasic.Devices.ComputerInfo().OSFullName);

                var osQuery = new WqlObjectQuery("SELECT * FROM Win32_OperatingSystem");
                var objSearcher = new ManagementObjectSearcher(osQuery);
                var sysOsProductId = string.Empty;
                foreach (var obj in objSearcher.Get())
                {
                    sysOsProductId = ("OS Product ID: " + obj["SerialNumber"]);
                }

                var biosQuery = new WqlObjectQuery("SELECT * FROM Win32_Bios");
                objSearcher = new ManagementObjectSearcher(biosQuery);
                var biosName = string.Empty;
                foreach (var obj in objSearcher.Get())
                {
                    biosName = "Bios: " + obj["Name"];
                }

                var machineName = string.Format("Machine name: {0}", Environment.MachineName);
                var userName = string.Format("User: {0}", Environment.UserName);
                var userDomainName = string.Format("Domain: {0}", Environment.UserDomainName);
                var cpuName = string.Format("CPU: {0}", Registry.LocalMachine
                    .OpenSubKey(@"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0")
                    ?.GetValue(@"ProcessorNameString") ?? "no data");
                var monitorSize = string.Format("Display size: Height: {0} Width: {1}",
                    PrimaryMonitorSize.Height, PrimaryMonitorSize.Width);
                var drives = DriveInfo.GetDrives();
                var totalRam = string.Format("RAM: {0}",
                    new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);

                // PRINT LOG SYSTEM INFO
                sysInfoListView.Items.Add(sysDirectory);
                sysInfoListView.Items.Add(sysRunTime);
                sysInfoListView.Items.Add(sysOsVersion);
                sysInfoListView.Items.Add(sysOsName);
                sysInfoListView.Items.Add(sysOsProductId);
                sysInfoListView.Items.Add(biosName);
                sysInfoListView.Items.Add(machineName);
                sysInfoListView.Items.Add(userName);
                sysInfoListView.Items.Add(userDomainName);
                sysInfoListView.Items.Add(cpuName);
                sysInfoListView.Items.Add(totalRam);

                foreach (var driveName in
                    from drive in drives
                    let driveName = "Disk drive " + drive.Name
                    select driveName + (drive.IsReady
                    ? " Format: " + drive.DriveFormat + " Total size: " + drive.TotalSize
                    : " Drive is not ready"))
                {
                    sysInfoListView.Items.Add(driveName);
                }

                sysInfoListView.Items.Add(monitorSize);
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #29
0
        public static string GetExecutableOfService(string serviceName)
        {
            var wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName));
            using (var managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery))
            {
                var managementObjectCollection = managementObjectSearcher.Get();

                return (
                            from ManagementObject managementObject in managementObjectCollection 
                            select managementObject.GetPropertyValue("PathName").ToString()
                            into executableOfService 
                            select ParseExePath(executableOfService)
                        ).FirstOrDefault();
            }
        }
예제 #30
0
        protected void buildSCCMInfo(string resourceID)
        {
            /*
             *     strQuery = "SELECT * FROM SMS_FullCollectionMembership WHERE ResourceID="& computerID
                    for each fc in foundCollections
                       Set collection = SWbemServices.Get ("SMS_Collection.CollectionID=""" & fc.CollectionID &"""")
                       stringResult = stringResult & "<li> "  & collection.Name & "<br />"
                Next

             * SMS_Collection.CollectionID =
             *
             */

            //XXX: remeber to filter out computers that are obsolite in sccm (not active)
            var sb = new StringBuilder();

            var ms = new ManagementScope("\\\\srv-cm12-p01.srv.aau.dk\\ROOT\\SMS\\site_AA1");
            var wqlq = new WqlObjectQuery("SELECT * FROM SMS_FullCollectionMembership WHERE ResourceID=" + resourceID);
            var searcher = new ManagementObjectSearcher(ms, wqlq);

            ManagementObject obj = new ManagementObject();
            var results = searcher.Get();

            bool hasValues=false;
            try
            {
                var t = results.Count;
                hasValues=true;
            }catch (ManagementException e){}

            string configPC = "Unknown";
            string configExtra = "False";
            string getsTestUpdates = "False";

            if (hasValues)
            {
                foreach (ManagementObject o in results)
                {
                    //o.Properties["ResourceID"].Value.ToString();
                    var collectionID = o.Properties["CollectionID"].Value.ToString();

                    if (collectionID.Equals("AA100015"))
                    {
                        configPC = "AAU PC";
                    }else if (collectionID.Equals("AA100087")){
                        configPC = "AAU8 PC";
                    }
                    else if (collectionID.Equals("AA1000BC"))
                    {
                        configPC = "AAU10 PC";
                        configExtra = "True"; // Hardcode AAU10 is bitlocker enabled
                    }
                    else if (collectionID.Equals("AA100027"))
                    {
                        configPC = "Administrativ PC";
                    }
                    else if (collectionID.Equals("AA10009C"))
                    {
                        configPC = "Imported";
                    }

                    if (collectionID.Equals("AA1000B8"))
                    {
                        configExtra = "True";
                    }

                    if (collectionID.Equals("AA100069") || collectionID.Equals("AA100066") || collectionID.Equals("AA100065") || collectionID.Equals("AA100064") || collectionID.Equals("AA100063") || collectionID.Equals("AA100083"))
                    {
                        getsTestUpdates = "True";
                    }

                    var pathString = "\\\\srv-cm12-p01.srv.aau.dk\\ROOT\\SMS\\site_AA1" + ":SMS_Collection.CollectionID=\"" + collectionID + "\"";
                    ManagementPath path = new ManagementPath(pathString);

                    obj.Path = path;
                    obj.Get();

                    sb.Append(string.Format("{0}<br/>", obj["Name"]));
                }
            }
            else
            {
                sb.Append("Computer not found i SCCM");
            }

            labelBasicInfoPCConfig.Text = configPC;
            labelBasicInfoExtraConfig.Text = configExtra;
            labelBasicInfoTestUpdates.Text = getsTestUpdates;

            //Basal Info
            var wqlqSystem = new WqlObjectQuery("SELECT * FROM SMS_R_System WHERE ResourceId=" + resourceID);
            var searcherSystem = new ManagementObjectSearcher(ms, wqlqSystem);

            ManagementObject objSystem = new ManagementObject();
            var resultsSystem = searcherSystem.Get();

            hasValues = false;
            try
            {
                var t2 = resultsSystem.Count;
                hasValues = true;
            }
            catch (ManagementException e) {}

            sb.Append("<h3>Computer Details</h3>");

            if (hasValues)
            {

                foreach (ManagementObject o in resultsSystem) //Has one!
                {
                    //OperatingSystemNameandVersion = Microsoft Windows NT Workstation 6.1

                    foreach (var property in o.Properties)
                    {
                        string key = property.Name;
                        object value = property.Value;

                        int i = 0;
                        string[] arry = null;
                        if (value != null && value.GetType().IsArray)
                        {
                            if (value is string[]){
                                arry = (string[])value;
                            } else {
                                arry = new string[]{ "none-string value" }; //XXX get the byte value
                            }
                            foreach (string f in arry)
                            {
                                sb.Append(string.Format("{0}[{2}]: {1}<br />", key, f, i));
                                i++;
                            }
                        }
                        else
                        {
                            sb.Append(string.Format("{0}: {1}<br />", key, property.Value));
                        }

                    }

                }
            }
            else
            {
                sb.Append("Computer not found i SCCM");
            }

            labelSCCMCollections.Text = sb.ToString();
        }