Example #1
2
        //private char NULL_VALUE = char(0);
        public static ProcessReturnCode Run(string machineName, string commandLine, string args, string currentDirectory)
        {
            var connOptions = new ConnectionOptions
                                  {
                                      EnablePrivileges = true
                                  };

            var scope = new ManagementScope(@"\\{0}\root\cimv2".FormatWith(machineName), connOptions);
            scope.Connect();
            var managementPath = new ManagementPath(CLASSNAME);
            using (var processClass = new ManagementClass(scope, managementPath, new ObjectGetOptions()))
            {
                var inParams = processClass.GetMethodParameters("Create");
                commandLine = System.IO.Path.Combine(currentDirectory, commandLine);
                inParams["CommandLine"] = "{0} {1}".FormatWith(commandLine, args);

                var outParams = processClass.InvokeMethod("Create", inParams, null);

                var rtn = Convert.ToUInt32(outParams["returnValue"]);
                var pid = Convert.ToUInt32(outParams["processId"]);
                if (pid != 0)
                {
                    WaitForPidToDie(machineName, pid);
                }

                return (ProcessReturnCode)rtn;
            }
        }
Example #2
1
        static void Main(string[] args)
        {
            ConnectionOptions conn = new ConnectionOptions();
            conn.Username = "******";//登入远端电脑的账户
            conn.Password = "******";//登入远端电脑的密码
            ManagementPath path = new ManagementPath();

            //其中root\cimv2是固定写法
            path.Path = @"\\10.0.1.36\root\cimv2";
            ManagementScope ms = new ManagementScope();
            ms.Options = conn;
            ms.Path = path;
            ms.Connect();
            //这里的例子读取文件的最后修改日期
            ObjectQuery query = new ObjectQuery("SELECT * FROM CIM_DataFile WHERE Name = 'C:\\\\KVOffice.txt'");
            ManagementObjectSearcher  searcher = new ManagementObjectSearcher(ms,query);
            ManagementObjectCollection collection = searcher.Get();
            string time = "";
            foreach (ManagementObject obj in collection)
            {
                time = obj.Properties["LastModified"].Value.ToString().Substring(0,14);
            }
            Console.WriteLine("测试dev");
            Console.WriteLine(time);
            Console.ReadLine();
        }
        //Create a system restore point using WMI. Should work in XP, VIsta and 7
        private void buttonSystemRestore_Click(object sender, EventArgs e)
        {
            ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default");
            ManagementPath oPath = new ManagementPath("SystemRestore");
            ObjectGetOptions oGetOp = new ObjectGetOptions();
            ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp);

            ManagementBaseObject oInParams = oProcess.GetMethodParameters("CreateRestorePoint");
            oInParams["Description"] = "Nvidia PowerMizer Manager";
            oInParams["RestorePointType"] = 10;
            oInParams["EventType"] = 100;

            this.buttonOK.Enabled = false;
            this.buttonCancel.Enabled = false;
            this.buttonSystemRestore.Enabled = false;

            this.labelDis.Text = "Creating System Restore Point. Please wait...";

            ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null);

            this.buttonOK.Enabled = true;
            this.buttonCancel.Enabled = true;
            this.buttonSystemRestore.Enabled = true;

            this.labelDis.Text = text;
        }
 private ManagementScope ConnectToClient(string hostname)
 {
     ManagementPath oPath = new ManagementPath(string.Format("\\\\{0}\\ROOT\\CCM", hostname));
     ConnectionOptions oCon = new ConnectionOptions();
     oCon.Impersonation = ImpersonationLevel.Impersonate;
     oCon.EnablePrivileges = true;
     ManagementScope oMs = new ManagementScope(oPath, oCon);
     try
     {
         oMs.Connect();
     }
     catch (System.UnauthorizedAccessException ex)
     {
         return null;
     }
     catch (Exception e)
     {
         return null;
     }
     finally
     {
         GC.Collect();
     }
     return oMs;
 }
        /// <summary>
        /// </summary>
        /// <param name="objz"></param>
        /// <param name="cmdTag"></param>
        /// <returns></returns>
        public static bool ChangeServiceStartMode(WmiServiceObj objz, string cmdTag)
        {
            bool bRel;
            var sc = new ServiceController(objz.Name);
            string startupType = "";

            var myPath = new ManagementPath
            {
                Server = Environment.MachineName,
                NamespacePath = @"root\CIMV2",
                RelativePath = string.Format("Win32_Service.Name='{0}'", sc.ServiceName)
            };
            switch (cmdTag)
            {
                case "41":
                    startupType = "Manual";
                    break;
                case "42":
                    startupType = "Auto";
                    break;
                case "43":
                    startupType = "Disabled";
                    break;
            }
            using (var service = new ManagementObject(myPath))
            {
                ManagementBaseObject inputArgs = service.GetMethodParameters("ChangeStartMode");
                inputArgs["startmode"] = startupType;
                service.InvokeMethod("ChangeStartMode", inputArgs, null);
                bRel = true;
            }

            sc.Refresh();
            return bRel;
        }
Example #6
0
        public void Bob()
        {
            var connOptions = new ConnectionOptions
                                  {
                                      EnablePrivileges = true,
                                      //Username = "******",
                                      //Password = "******"
                                  };

            string server = "SrvTestWeb01";
            ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", server), connOptions);
            manScope.Connect();
            

            var managementPath = new ManagementPath("Win32_Process");
            var processClass = new ManagementClass(manScope, managementPath, new ObjectGetOptions());

            var inParams = processClass.GetMethodParameters("Create");
            inParams["CommandLine"] = @"C:\Temp\dropkick.remote\dropkick.remote.exe create_queue msmq://localhost/dk_test";

            var outParams = processClass.InvokeMethod("Create", inParams, null);

            var rtn = System.Convert.ToUInt32(outParams["returnValue"]);
            var processID = System.Convert.ToUInt32(outParams["processId"]);
        }
Example #7
0
		protected WmiEventSink(ManagementOperationObserver watcher, object context, ManagementScope scope, string path, string className)
		{
			try
			{
				this.context = context;
				this.watcher = watcher;
				this.className = className;
				this.isLocal = false;
				if (path != null)
				{
					this.path = new ManagementPath(path);
					if (string.Compare(this.path.Server, ".", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(this.path.Server, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0)
					{
						this.isLocal = true;
					}
				}
				if (scope != null)
				{
					this.scope = scope.Clone();
					if (path == null && (string.Compare(this.scope.Path.Server, ".", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(this.scope.Path.Server, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0))
					{
						this.isLocal = true;
					}
				}
				WmiNetUtilsHelper.GetDemultiplexedStub_f(this, this.isLocal, out this.stub);
				this.hash = Interlocked.Increment(ref WmiEventSink.s_hash);
			}
			catch
			{
			}
		}
Example #8
0
 public WmiWrapper(ManagementPath path)
 {
     _scope = new ManagementScope(path)
     {
         Options = { Impersonation = ImpersonationLevel.Impersonate }
     };
 }
        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 void LoadDeviceList()
        {
            devices.Clear();
            devices.Add(new SoundDevice("Default", "0000", "0000"));

            ManagementPath path = new ManagementPath();
            ManagementClass devs = null;
            path.Server = ".";
            path.NamespacePath = @"root\CIMV2";
            path.RelativePath = @"Win32_SoundDevice";
            using (devs = new ManagementClass(new ManagementScope(path), path, new ObjectGetOptions(null, new TimeSpan(0, 0, 0, 2), true)))
            {
                ManagementObjectCollection moc = devs.GetInstances();

                foreach (ManagementObject mo in moc)
                {
                    PropertyDataCollection devsProperties = mo.Properties;
                    string devid = devsProperties["DeviceID"].Value.ToString();
                    if (devid.Contains("PID_"))
                    {
                        string vid = devid.Substring(devid.IndexOf("VID_") + 4, 4);
                        string pid = devid.Substring(devid.IndexOf("PID_") + 4, 4);

                        devices.Add(new SoundDevice(devsProperties["Caption"].Value.ToString(), vid, pid));

                    }
                }
            }
        }
Example #11
0
        protected void addComputerToCollection(string resourceID, string collectionID)
        {
            /*  Set collection = SWbemServices.Get ("SMS_Collection.CollectionID=""" & CollID &"""")

                  Set CollectionRule = SWbemServices.Get("SMS_CollectionRuleDirect").SpawnInstance_()
                  CollectionRule.ResourceClassName = "SMS_R_System"
                  CollectionRule.RuleName = "Static-"&ResourceID
                  CollectionRule.ResourceID = ResourceID
                  collection.AddMembershipRule CollectionRule*/

            //o.Properties["ResourceID"].Value.ToString();

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

            ManagementClass ruleClass = new ManagementClass("\\\\srv-cm12-p01.srv.aau.dk\\ROOT\\SMS\\site_AA1" + ":SMS_CollectionRuleDirect");

            ManagementObject rule = ruleClass.CreateInstance();

            rule["RuleName"] = "Static-"+ resourceID;
            rule["ResourceClassName"] = "SMS_R_System";
            rule["ResourceID"] = resourceID;

            obj.InvokeMethod("AddMembershipRule", new object[] { rule });
        }
        public bool CheckDeviceMacadress(string strMacadress)
        {
           
            MacAdress = strMacadress;
           
            ManagementPath cmPath = new ManagementPath("root\\sms\\site_PS1:SMS_R_SYSTEM"); 
            ManagementClass cmClass = new ManagementClass(cmPath);
            ManagementObjectCollection cmCollection = cmClass.GetInstances();

            DeviceFound = false;

            foreach (ManagementObject deviceInfo in cmCollection)
            {
                string[] listCmDeviceMacAdresses = (string[])deviceInfo["MACAddresses"];
                foreach (string MacAdressExist in listCmDeviceMacAdresses)
                {
                    if (MacAdressExist == MacAdress)
                    {
                        DeviceFound = true;
                    }
                    
                }
         
            }

            return DeviceFound;
        }
        private List<String> RemoteComputerInfo(string Username, string Password, string IP, string sWin32class)
        {
            List<String> resultList = new List<String>();

            ConnectionOptions options = new ConnectionOptions();
            options.Username = Username;
            options.Password = Password;
            options.Impersonation = ImpersonationLevel.Impersonate;
            options.EnablePrivileges = true;
            try
            {
                ManagementScope mgtScope = new ManagementScope(string.Format("\\\\{0}\\root\\cimv2", IP), options);
                mgtScope.Connect();

                ObjectGetOptions objectGetOptions = new ObjectGetOptions();
                ManagementPath mgtPath = new ManagementPath(sWin32class);
                ManagementClass mgtClass = new ManagementClass(mgtScope, mgtPath, objectGetOptions);

                PropertyDataCollection prptyDataCollection = mgtClass.Properties;

                foreach (ManagementObject mgtObject in mgtClass.GetInstances())
                {
                    foreach (PropertyData property in prptyDataCollection)
                    {
                        try
                        {
                            string mobjvalue = "";
                            if (mgtObject.Properties[property.Name].Value == null)
                            {
                                mobjvalue = "null";
                            }
                            else
                            {
                                mobjvalue = mgtObject.Properties[property.Name].Value.ToString();
                            }

                            if (ShouldInclude(property.Name))
                            {
                                resultList.Add(string.Format(property.Name + ":  " + mobjvalue));
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                resultList.Add(string.Format("Can't Connect to Server: {0}\n{1}", IP, ex.Message));
            }

            return resultList;
        }
Example #14
0
        //private Provider oProv;

        public WMIProvider(string hostname)
        {
            oRootPath = new ManagementPath(string.Format("\\\\{0}\\ROOT\\CIMV2", hostname));
            //oCCMPath = new ManagementPath(string.Format("\\\\{0}\\ROOT\\CCM", hostname));
            oCon.Impersonation = ImpersonationLevel.Impersonate;
            oCon.EnablePrivileges = true;
            oRootMs = new ManagementScope(oRootPath, oCon);
            this.Hostname = hostname;
            //oProv = new Provider(oRootPath.NamespacePath);
            
        }
 internal ManagementScope(ManagementPath path, IWbemServices wbemServices, ConnectionOptions options)
 {
     if (path != null)
     {
         this.Path = path;
     }
     if (options != null)
     {
         this.Options = options;
     }
     this.wbemServices = wbemServices;
 }
Example #16
0
        private void addIPPort()
        {
            var conn = new ConnectionOptions
            {
                EnablePrivileges = true,
                Impersonation = ImpersonationLevel.Impersonate
            };

            var mPath = new ManagementPath("Win32_TCPIPPrinterPort");

            var mScope = new ManagementScope(@"\\.\root\cimv2", conn)
            {
                Options =
                {
                    EnablePrivileges = true,
                    Impersonation = ImpersonationLevel.Impersonate
                }
            };

            var mPort = new ManagementClass(mScope, mPath, null).CreateInstance();

            var remotePort = 9100;

            try
            {
                if (IP != null && IP.Contains(":"))
                {
                    var arIP = IP.Split(':');
                    if (arIP.Length == 2)
                        remotePort = int.Parse(arIP[1]);
                }
            }
            catch (Exception ex)
            {
                Log.Error(LogName, "Could not parse port from IP");
                Log.Error(LogName, ex);
            }

            mPort.SetPropertyValue("Name", Port);
            mPort.SetPropertyValue("Protocol", 1);
            mPort.SetPropertyValue("HostAddress", IP);
            mPort.SetPropertyValue("PortNumber", remotePort);
            mPort.SetPropertyValue("SNMPEnabled", false);

            var put = new PutOptions
            {
                UseAmendedQualifiers = true,
                Type = PutType.UpdateOrCreate
            };
            mPort.Put(put);
        }
 internal static ManagementPath _Clone(ManagementPath path, IdentifierChangedEventHandler handler)
 {
     ManagementPath path2 = new ManagementPath();
     if (handler != null)
     {
         path2.IdentifierChanged = handler;
     }
     if ((path != null) && (path.wmiPath != null))
     {
         path2.wmiPath = path.wmiPath;
         path2.isWbemPathShared = path.isWbemPathShared = true;
     }
     return path2;
 }
        public static void Main(string[] args)
        {
            var now = DateTime.Now.ToString();
            var filepath = Environment.CurrentDirectory + @"\output.txt";
            Console.WriteLine("Fetching information about BitLocker using WIM ..\r\n");
            using (var file = File.CreateText(filepath))
            {
                try
                {
                    var path = new ManagementPath();
                    path.NamespacePath = BITLOCKER_NS;
                    path.ClassName = BITLOCKER_CLASS;

                    var scope = new ManagementScope(path);
                    var options = new ObjectGetOptions();
                    var management = new ManagementClass(scope, path, options);

                    file.WriteLine(string.Format("{0}\r\n", now));
                    int counter = 1;
                    foreach (var instance in management.GetInstances())
                    {
                        var builder = new StringBuilder();
                        builder.AppendFormat("{0}.\r\n", counter);
                        builder.AppendFormat("  DeviceID:            {0}\r\n", instance["DeviceID"]);
                        builder.AppendFormat("  PersistentVolumeID:  {0}\r\n", instance["PersistentVolumeID"]);
                        builder.AppendFormat("  DriveLetter:         {0}\r\n", instance["DriveLetter"]);
                        builder.AppendFormat("  ProtectionStatus:    {0}\r\n", instance["ProtectionStatus"]);

                        Console.WriteLine(builder.ToString());
                        file.Write(builder.ToString());
                        counter++;
                    }
                    file.Flush();

                    Console.WriteLine("Output written to: " + filepath);
                }
                catch (Exception ex)
                {
                    file.WriteLine(ex.Message);
                    Console.WriteLine(ex.Message);
                    file.WriteLine(ex.StackTrace);
                    Console.WriteLine(ex.StackTrace);
                }
                finally
                {
                    Console.WriteLine("\r\nPress Enter to continue ..");
                    Console.ReadLine();
                }
            }
        }
Example #19
0
        /// <summary>
        /// Common utility function to get a service object.
        /// </summary>
        /// <param name="scope">The management scope that is used to connect to WMI.</param>
        /// <param name="serviceName">The name of the service through which the object should be obtained.</param>
        /// <returns>The desired management object, or <see langword="null" />.</returns>
        public static ManagementObject GetServiceObject(ManagementScope scope, string serviceName)
        {
            scope.Connect();
            var wmiPath = new ManagementPath(serviceName);
            var serviceClass = new ManagementClass(scope, wmiPath, null);
            var services = serviceClass.GetInstances();

            ManagementObject serviceObject = null;
            foreach (ManagementObject service in services)
            {
                serviceObject = service;
            }

            return serviceObject;
        }
 public bool AppPoolAction(string action)
 {
     bool bSuccess = false;
     _options.Authentication = AuthenticationLevel.PacketPrivacy;
     var scope = new ManagementScope(@"\\" + _sHost + "\\root\\MicrosoftIISv2", _options);
     try
     {
         scope.Connect();
         var path = new ManagementPath("IIsApplicationPool='W3SVC/AppPools/" + _sPoolName + "'");
         var pool = new ManagementObject(scope, path, null);
         switch (action.ToLower())
         {
             case "stop":
                 Console.Write("Stopping \"{0}\" on \"{1}\"...\n", _sPoolName, _sHost);
                 LogWriter.WriteLog(DateTime.Now, "Stopping " + _sPoolName + " on " + _sHost);
                 pool.InvokeMethod("Stop", new object[0]);
                 bSuccess = true;
                 Console.WriteLine("Stopping is done \n");
                 LogWriter.WriteLog(DateTime.Now, "Stopping is done on " + _sHost);
                 break;
             case "start":
                 Console.WriteLine("Starting \"{0}\" on \"{1}\"...\n", _sPoolName, _sHost);
                 LogWriter.WriteLog(DateTime.Now, "Starting " + _sPoolName + " on " + _sHost);
                 pool.InvokeMethod("Start", new object[0]);
                 bSuccess = true;
                 Console.WriteLine("Starting is done \n");
                 LogWriter.WriteLog(DateTime.Now, "Starting is done on" + _sHost);
                 break;
             case "recycle":
                 Console.WriteLine("Recycling \"{0}\" on \"{1}\"...\n", _sPoolName, _sHost);
                 LogWriter.WriteLog(DateTime.Now, "Recycling " + _sPoolName + " on " + _sHost);
                 pool.InvokeMethod("Recycle", new object[0]);
                 bSuccess = true;
                 Console.WriteLine("Recycling is done \n");
                 LogWriter.WriteLog(DateTime.Now, "Recycling is done on " + _sHost);
                 break;
             default:
                 Console.WriteLine("Incorrect operation. Operations can be start,stop,recyle");
                 LogWriter.WriteLog(DateTime.Now, "Incorrect operation. Operations can be is start,stop,recycle");
                 break;
         }
     }
     catch (Exception ex)
     {
         HostAccessExceptionHandler(ex);
     }
     return bSuccess;
 }
Example #21
0
        public ManagementObject GetMetaInformation(string name)
        {
            ManagementObject value = null;
            ManagementScope scope = new ManagementScope(@"\\localhost");

            ManagementPath path = new ManagementPath(name);
            ManagementClass management = new ManagementClass(scope, path, null);

            foreach (ManagementObject child in management.GetInstances())
            {
                value = child;
                break;
            }
            management.Dispose();
            return value;
        }
 public string GetStartupType()
 {
     if (this.ServiceName != null)
     {
         //construct the management path
         string path = "Win32_Service.Name='" + this.ServiceName + "'";
         ManagementPath p = new ManagementPath(path);
         //construct the management object
         ManagementObject ManagementObj = new ManagementObject(p);
         return ManagementObj["StartMode"].ToString();
     }
     else
     {
         return null;
     }
 }
        public static ManagementObject GetVSMS(string Server)
        {
            ManagementScope scope = new ManagementScope($@"\\{Server}\root\virtualization\v2");
            scope.Connect();

            ManagementPath wmiPath = new ManagementPath("Msvm_VirtualSystemManagementService");
            ManagementClass serviceClass = new ManagementClass(scope, wmiPath, null);
            ManagementObjectCollection services = serviceClass.GetInstances();

            ManagementObject serviceObject = null;

            foreach (ManagementObject service in services)
            {
                serviceObject = service;
            }
            return serviceObject;
        }
        /*
         *Method that execute a WMI command on a remote computer and return all the profile folders' name
         * in an arraylist
         */
        public static ArrayList getProfile(string computername)
        {
            //List to store the user profiles
            ArrayList profileList = new ArrayList();

            //Line of the file written on the client
            string line;

            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();
            InvokeMethodOptions methodOptions = new InvokeMethodOptions(null, System.TimeSpan.MaxValue);
            ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);
            ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

            //The command to execute to get the profile folder and write the result to C:\\tmp.txt
            inParams["CommandLine"] = "cmd /c " + "dir C:\\Users /B" + " > c:\\tmp.txt";
            ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams,methodOptions);

            //Arbitratry delay to make sure that the command is done
            Thread.Sleep(2000);

            //Reading the result file
            StreamReader sr = new StreamReader("\\\\" + computername + "\\c$\\tmp.txt");
            line = sr.ReadLine();

            //While there are profile
            while (line != null)
            {
              //Add the profile to the arraylist
              profileList.Add(line);
              line = sr.ReadLine();

            }

            sr.Close();

            return profileList;
        }
        const int delayInAutoEventTimeout = 400; // 400 milliseconds

        internal RemoteHelper(string machineName)
        {
            this.machineName = machineName;

            // establish connection
            ConnectionOptions co = new ConnectionOptions();
            co.Authentication = AuthenticationLevel.PacketPrivacy;
            co.Impersonation = ImpersonationLevel.Impersonate;

            // define the management scope
            managementScope = new ManagementScope("\\\\" + machineName + "\\root\\cimv2", co);
            // define the path used
            ManagementPath path = new ManagementPath("Win32_Process");
            ObjectGetOptions options = new ObjectGetOptions(new ManagementNamedValueCollection(), TimeSpan.FromSeconds(15), false);

            // get the object for the defined path in the defined scope
            // this object will be the object on which the InvokeMethod will be called
            processClass = new ManagementClass(managementScope, path, options);
        }
        GetGeneration2BootOrder(
            string serverName,
            string vmName)
        {
            ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null);

            using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope))
            using (ManagementObject vmSettings = WmiUtilities.GetVirtualMachineSettings(vm))
            {
                // Determine the generation of this VM.
                string virtualSystemSubType = (string)vmSettings["VirtualSystemSubType"];
                UInt16 networkBootPreferredProtocol = (UInt16)vmSettings["NetworkBootPreferredProtocol"];

                if (!string.Equals(virtualSystemSubType, "Microsoft:Hyper-V:SubType:2", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("VM {0} on server {1} is not generation 2", vmName, serverName);
                    return;
                }

                string[] bootOrder = (string[])vmSettings["BootSourceOrder"];
                int index = 0;

                Console.WriteLine("NetworkBootPreferredProtocol = {0}", networkBootPreferredProtocol);
                Console.WriteLine("BootSourceOrder:");

                foreach (string entry in bootOrder)
                {
                    Console.WriteLine("Entry {0}:", index++);

                    ManagementPath entryPath = new ManagementPath(entry);

                    using (ManagementObject entryObject = new ManagementObject(entryPath))
                    {
                        Console.WriteLine("    BootSourceDescription    = {0}", entryObject["BootSourceDescription"]);
                        Console.WriteLine("    BootSourceType           = {0}", entryObject["BootSourceType"]);
                        Console.WriteLine("    OtherLocation            = {0}", entryObject["OtherLocation"]);
                        Console.WriteLine("    FirmwareDevicePath");
                        Console.WriteLine("        {0}", entryObject["FirmwareDevicePath"]);
                        Console.WriteLine();
                    }
                }
            }
        }
Example #27
0
 /// <summary>
 /// Loads applications
 /// </summary>
 /// <param name="Name">Computer name</param>
 /// <param name="UserName">User name</param>
 /// <param name="Password">Password</param>
 private void LoadApplications(string Name, string UserName, string Password)
 {
     ApplicationList = new List<Application>();
     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\\default", Options);
     }
     else
     {
         Scope = new ManagementScope("\\\\" + Name + "\\root\\default");
     }
     ManagementPath Path = new ManagementPath("StdRegProv");
     using (ManagementClass Registry = new ManagementClass(Scope, Path, null))
     {
         const uint HKEY_LOCAL_MACHINE = unchecked((uint)0x80000002);
         object[] Args = new object[] { HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", null };
         uint MethodValue = (uint)Registry.InvokeMethod("EnumKey", Args);
         string[] Keys = Args[2] as String[];
         using (ManagementBaseObject MethodParams = Registry.GetMethodParameters("GetStringValue"))
         {
             MethodParams["hDefKey"] = HKEY_LOCAL_MACHINE;
             foreach (string SubKey in Keys)
             {
                 MethodParams["sSubKeyName"] = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + SubKey;
                 MethodParams["sValueName"] = "DisplayName";
                 using (ManagementBaseObject Results = Registry.InvokeMethod("GetStringValue", MethodParams, null))
                 {
                     if (Results != null && (uint)Results["ReturnValue"] == 0)
                     {
                         Application Temp = new Application();
                         Temp.Name = Results["sValue"].ToString();
                         ApplicationList.Add(Temp);
                     }
                 }
             }
         }
     }
 }
Example #28
0
        /// <summary>
        /// Targets the specified namespace on a specified computer, and scavenges it for all classes, if the bool is set to true. If false, it is used to setup the ManagementPath which
        /// consists of the specified system and specified namespace
        /// </summary>
        /// <param name="pNamespace"></param>
        /// <param name="pHostName"></param>
        public WmiInformationGatherer(string pNamespace, string pHostName, bool pScavenge)
        {
            mRemoteWmiPath = new ManagementPath(@"\\" + pHostName + @"\root\" + pNamespace);

            if (pScavenge)
            {
                try
                {
                    ManagementClass managementClass = new ManagementClass(mRemoteWmiPath);
                    EnumerationOptions scavengeOptions = new EnumerationOptions();
                    scavengeOptions.EnumerateDeep = false;
                    WmiResults = new WmiResult(pHostName);
                    WmiResults.PopulateClassesList(managementClass.GetSubclasses());
                }
                catch (Exception e)
                {
                    WmiResults.WmiError = e;
                }
            }
        }
 public RelationshipQuery(string queryOrSourceObject)
 {
     if (queryOrSourceObject != null)
     {
         if (queryOrSourceObject.TrimStart(new char[0]).StartsWith(tokenReferences, StringComparison.OrdinalIgnoreCase))
         {
             this.QueryString = queryOrSourceObject;
         }
         else
         {
             ManagementPath path = new ManagementPath(queryOrSourceObject);
             if ((!path.IsClass && !path.IsInstance) || (path.NamespacePath.Length != 0))
             {
                 throw new ArgumentException(RC.GetString("INVALID_QUERY"), "queryOrSourceObject");
             }
             this.SourceObject = queryOrSourceObject;
             this.isSchemaQuery = false;
         }
     }
 }
 public SelectQuery(string queryOrClassName)
 {
     this.selectedProperties = new StringCollection();
     if (queryOrClassName != null)
     {
         if (queryOrClassName.TrimStart(new char[0]).StartsWith(ManagementQuery.tokenSelect, StringComparison.OrdinalIgnoreCase))
         {
             this.QueryString = queryOrClassName;
         }
         else
         {
             ManagementPath path = new ManagementPath(queryOrClassName);
             if (!path.IsClass || (path.NamespacePath.Length != 0))
             {
                 throw new ArgumentException(RC.GetString("INVALID_QUERY"), "queryOrClassName");
             }
             this.ClassName = queryOrClassName;
         }
     }
 }
 public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
 public WmiMonitorBrightnessEvent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path)
 {
     this.InitializeObject(mgmtScope, path, null);
 }
Example #33
0
 public HostInstanceSetting(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path)
 {
     this.InitializeObject(mgmtScope, path, null);
 }
 public BcdObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
 public BcdObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path)
 {
     this.InitializeObject(mgmtScope, path, null);
 }
Example #36
0
 public RegistryTreeChangeEvent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
Example #37
0
 public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
Example #38
0
 public StorageAllocationSettingData(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }
Example #39
0
 public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }
Example #40
0
 public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
 public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path)
 {
     this.InitializeObject(mgmtScope, path, null);
 }
 public EthernetPortAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
Example #43
0
 public SendHandler2(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path)
 {
     this.InitializeObject(mgmtScope, path, null);
 }
Example #44
0
 public SendHandler2(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }
Example #45
0
 public MemorySettingData(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }
Example #46
0
 public WmiMonitorBrightness(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }
Example #47
0
 public RegistryTreeChangeEvent(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }
Example #48
0
 public WmiMonitorBrightness(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
 public BcdObject(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
Example #50
0
 public ProcessorSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
 public BcdObject(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }
Example #52
0
 public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path)
 {
     this.InitializeObject(mgmtScope, path, null);
 }
Example #53
0
 public HostInstanceSetting(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
 public SyntheticEthernetPortSettingData(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }
 public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
Example #56
0
 public RegistryValueChangeEvent(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
 public WmiMonitorBrightnessEvent(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
Example #58
0
 public RegistryValueChangeEvent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path)
 {
     this.InitializeObject(mgmtScope, path, null);
 }
Example #59
0
 public SystemRestore(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }
Example #60
0
 public WmiEnvironment(System.Management.ManagementPath path)
 {
     this.InitializeObject(null, path, null);
 }