//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;
        }
        public static String[] getComputerInfos(string computername)
        {
            String[] computerInfos = new String[2];

            ConnectionOptions connOptions = new ConnectionOptions();
            ObjectGetOptions objectGetOptions = new ObjectGetOptions();
            ManagementPath managementPath = new ManagementPath("Win32_Process");

            //To use caller credential
            connOptions.Impersonation = ImpersonationLevel.Impersonate;
            connOptions.EnablePrivileges = true;
            ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", computername), connOptions);
            manScope.Connect();
            ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(manScope, query);
            ManagementObjectCollection queryCollection = searcher.Get();

            foreach (ManagementObject m in queryCollection){

                computerInfos[0] = Convert.ToString(m["Caption"]);
                computerInfos[1] = Convert.ToString(m["Status"]);

            }

            return computerInfos;
        }
        private static void ReportNow()
        {
            Logger.Write("Sending ReportNow.");
            try
            {
                ConnectionOptions connectoptions = new ConnectionOptions();

                System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(@"\\.\ROOT\CIMV2", connectoptions);
                mgmtScope.Connect();
                System.Management.ObjectGetOptions     objectGetOptions = new System.Management.ObjectGetOptions();
                System.Management.ManagementPath       mgmtPath         = new System.Management.ManagementPath("Win32_Process");
                System.Management.ManagementClass      processClass     = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions);
                System.Management.ManagementBaseObject inParams         = processClass.GetMethodParameters("Create");
                ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup");
                startupInfo.Properties["ShowWindow"].Value = 0;

                inParams["CommandLine"] = "WuAuClt.exe /ReportNow";
                inParams["ProcessStartupInformation"] = startupInfo;

                processClass.InvokeMethod("Create", inParams, null);
            }
            catch (Exception ex)
            {
                Logger.Write("Problem when doing ReportNow. " + ex.Message);
            }
            Logger.Write("ReportNow done.");
        }
Exemple #4
0
        private bool SendCommand(string command, string username, string password)
        {
            Logger.EnteringMethod(command);
            try
            {
                ConnectionOptions connectoptions = new ConnectionOptions();
                if (username != null && password != null && this.Name.ToLower() != GetFullyQualifiedDomainName().ToLower())
                {
                    connectoptions.Username = username;
                    connectoptions.Password = password;
                }
                connectoptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;

                System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", this.Name), connectoptions);
                mgmtScope.Connect();
                System.Management.ObjectGetOptions     objectGetOptions = new System.Management.ObjectGetOptions();
                System.Management.ManagementPath       mgmtPath         = new System.Management.ManagementPath("Win32_Process");
                System.Management.ManagementClass      processClass     = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions);
                System.Management.ManagementBaseObject inParams         = processClass.GetMethodParameters("Create");
                ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup");
                startupInfo.Properties["ShowWindow"].Value = 0;

                inParams["CommandLine"] = command;
                inParams["ProcessStartupInformation"] = startupInfo;

                processClass.InvokeMethod("Create", inParams, null);
                Logger.Write("Command Sent Successfuly on : " + this.Name);
            }
            catch (Exception ex)
            {
                Logger.Write("**** " + ex.Message);
                return(false);
            }
            return(true);
        }
        public static string InstallHosts(string ServerName, string HostName, string UserName, string Password, bool StartHost)
        {
            PutOptions options = new PutOptions();
            options.Type = PutType.CreateOnly;
            ObjectGetOptions bts_objOptions = new ObjectGetOptions();

            // Creating instance of BizTalk Host.
            ManagementClass bts_AdminObjClassServerHost = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_ServerHost", bts_objOptions);
            ManagementObject bts_AdminObjectServerHost = bts_AdminObjClassServerHost.CreateInstance();

            // Make sure to put correct Server Name,username and // password
            bts_AdminObjectServerHost["ServerName"] = ServerName;
            bts_AdminObjectServerHost["HostName"] = HostName;
            bts_AdminObjectServerHost.InvokeMethod("Map", null);

            ManagementClass bts_AdminObjClassHostInstance = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_HostInstance", bts_objOptions);
            ManagementObject bts_AdminObjectHostInstance = bts_AdminObjClassHostInstance.CreateInstance();

            bts_AdminObjectHostInstance["Name"] = "Microsoft BizTalk Server " + HostName + " " + ServerName;

            //Also provide correct user name and password.
            ManagementBaseObject inParams = bts_AdminObjectHostInstance.GetMethodParameters("Install");
            inParams["GrantLogOnAsService"] = false;
            inParams["Logon"] = UserName;
            inParams["Password"] = Password;

            bts_AdminObjectHostInstance.InvokeMethod("Install", inParams, null);
            
            if(StartHost)
                bts_AdminObjectHostInstance.InvokeMethod("Start", null);

            return "  Host - " + HostName + " - has been installed. \r\n";
        }
        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;
        }
        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();
                }
            }
        }
        //-------------------------------------------------------------------------
        // Initializes the EventQueryCondition object, to create a pointer
        // back to the parent WMIScripter form.
        //-------------------------------------------------------------------------
        public QueryConditionForm(QueryControl2 parent)
        {
            InitializeComponent();
            this.StoredValue = "";

            this.OperatorBox.Items.Add("=");
            this.OperatorBox.Items.Add("<>");
            this.OperatorBox.Items.Add(">");
            this.OperatorBox.Items.Add("<");
            this.OperatorBox.Items.Add("ISA");

            this.Q_Info = parent;

            this.PropertyList.DrawMode = DrawMode.OwnerDrawFixed;
            this.PropertyList.DrawItem += new DrawItemEventHandler(this.PropertyList_DrawItem);

            this.ValueList.DrawMode = DrawMode.OwnerDrawFixed;
            this.ValueList.DrawItem += new DrawItemEventHandler(this.ValueList_DrawItem);

            try
            {
                ObjectGetOptions op = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                ManagementClass mc = new ManagementClass(this.Q_Info.GetNamespaceName(),
                    this.Q_Info.GetClassName(), op);
                mc.Options.UseAmendedQualifiers = true;

                foreach (PropertyData property in mc.Properties)
                {
                    if (property.IsArray)
                    {
                        // Don't add it to the list.
                    }
                    else
                    {
                        this.PropertyList.Items.Add(property.Name);
                    }
                }

                if (this.PropertyList.Items.Count > 0)
                {
                    this.PropertyList.Text = this.PropertyList.Items[0].ToString();
                }

            }
            catch (ManagementException)
            {
                // Invalid Query, the class or namespace might be blank.  Do nothing.
            }
        }
Exemple #9
0
 private void TestCreate()
 {
     ConnectionOptions Conn = new ConnectionOptions();
     //Conn.Username = "******";
     //Conn.Password = "******";
     Conn.Impersonation = ImpersonationLevel.Impersonate;
     Conn.EnablePrivileges = true;
     ManagementScope ms = new ManagementScope(@"\\.\root\sbs", Conn);
     ms.Connect();
     ObjectGetOptions option = new ObjectGetOptions();
     ManagementClass mc = new ManagementClass(ms, new ManagementPath("sbs_user"), option);
     ManagementObject mo = mc.CreateInstance();
     mo["UserName"] = "******";
     mo.Put();
 }
Exemple #10
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            System.Management.ConnectionOptions connOptions =
                new System.Management.ConnectionOptions();

            connOptions.Impersonation    = System.Management.ImpersonationLevel.Impersonate;
            connOptions.EnablePrivileges = true;
            connOptions.Username         = "******";
            connOptions.Password         = "******";

            string compName = "chan-PC";

            System.Management.ManagementScope manScope =
                new System.Management.ManagementScope(
                    String.Format(@"\\{0}\ROOT\CIMV2", compName), connOptions);
            manScope.Connect();

            System.Management.ObjectGetOptions objectGetOptions =
                new System.Management.ObjectGetOptions();

            System.Management.ManagementPath managementPath =
                new System.Management.ManagementPath("Win32_Process");

            System.Management.ManagementClass processClass =
                new System.Management.ManagementClass(manScope, managementPath, objectGetOptions);

            System.Management.ManagementBaseObject inParams =
                processClass.GetMethodParameters("Create");

            inParams["CommandLine"] = @"c:\MalCode\hiWinForm.exe";

            System.Management.ManagementBaseObject outParams =
                processClass.InvokeMethod("Create", inParams, null);

            var returnvalue = outParams["returnValue"];

            if (outParams["returnValue"].ToString().Equals("0"))
            {
                MessageBox.Show("Process execution returned " + unchecked ((int)outParams["returnValue"]));
            }
            else
            {
                MessageBox.Show("No type specified " + unchecked ((int)outParams["returnValue"]));
            }
        }
        /*
         *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);
        }
Exemple #13
0
        /// <summary>
        /// create client agents on nodes and start agents using WMI
        /// </summary>
        public static void CreateClientAgents()
        {
            Parallel.ForEach(TestEngine.TestPackage.Nodes.NodeList, node =>
            {
                for (int i = 0; i < TestEngine.TestPackage.Nodes.NoOfClientsPerNode; i++)
                {
                    string clientNumber = i.ToString();
                    //copy exe and other files to client location and start the exe
                    string remoteServerName = node;
                    if (!Directory.Exists(@"\\" + remoteServerName + @"\C$\WCFLoadUI" + clientNumber))
                    {
                        Directory.CreateDirectory(@"\\" + remoteServerName + @"\C$\WCFLoadUI" + clientNumber);
                    }

                    foreach (string newPath in Directory.GetFiles(Environment.CurrentDirectory + @"\WCFService", "*.*",
                        SearchOption.AllDirectories))
                        File.Copy(newPath,
                            newPath.Replace(Environment.CurrentDirectory + @"\WCFService",
                                @"\\" + remoteServerName + @"\C$\WCFLoadUI" + clientNumber), true);

                    ConnectionOptions connectionOptions = new ConnectionOptions();

                    ManagementScope scope =
                        new ManagementScope(
                            @"\\" + remoteServerName + "." + Domain.GetComputerDomain().Name + @"\root\CIMV2",
                            connectionOptions);
                    scope.Connect();

                    ManagementPath p = new ManagementPath("Win32_Process");
                    ObjectGetOptions objectGetOptions = new ObjectGetOptions();

                    ManagementClass classInstance = new ManagementClass(scope, p, objectGetOptions);

                    ManagementBaseObject inParams = classInstance.GetMethodParameters("Create");

                    inParams["CommandLine"] = @"C:\WCFLoadUI"  + clientNumber + @"\WCFService.exe " + Environment.MachineName + " 9090";
                    inParams["CurrentDirectory"] = @"C:\WCFLoadUI" + clientNumber;
                    classInstance.InvokeMethod("Create", inParams, null);
                }
            });
        }
Exemple #14
0
        public void SendCommand(string hostname, string command, Credential credential)
        {
            ConnectionOptions connectoptions = GetConnectionOptions(hostname, credential);

            connectoptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;

            System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", hostname), connectoptions);
            mgmtScope.Connect();
            System.Management.ObjectGetOptions     objectGetOptions = new System.Management.ObjectGetOptions();
            System.Management.ManagementPath       mgmtPath         = new System.Management.ManagementPath("Win32_Process");
            System.Management.ManagementClass      processClass     = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions);
            System.Management.ManagementBaseObject inParams         = processClass.GetMethodParameters("Create");
            ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup");

            startupInfo.Properties["ShowWindow"].Value = 0;

            inParams["CommandLine"] = command;
            inParams["ProcessStartupInformation"] = startupInfo;

            processClass.InvokeMethod("Create", inParams, null);
        }
        static void Main(string[] args)
        {
            try
            {
                string ComputerName = "localhost";
                ManagementScope Scope;

                if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
                {
                    ConnectionOptions Conn = new ConnectionOptions();
                    Conn.Username  = "";
                    Conn.Password  = "";
                    Conn.Authority = "ntlmdomain:DOMAIN";
                    Scope = new ManagementScope(String.Format("\\\\{0}\\[WMINAMESPACE]", ComputerName), Conn);
                }
                else
                    Scope = new ManagementScope(String.Format("\\\\{0}\\[WMINAMESPACE]", ComputerName), null);

                Scope.Connect();
                ObjectGetOptions Options      = new ObjectGetOptions();
                ManagementPath Path           = new ManagementPath("[WMIPATH]");
                ManagementObject ClassInstance= new ManagementObject(Scope, Path, Options);
                ManagementBaseObject inParams = ClassInstance.GetMethodParameters("[WMIMETHOD]");
Exemple #16
0
		internal static ObjectGetOptions _Clone(ObjectGetOptions options, IdentifierChangedEventHandler handler)
		{
			ObjectGetOptions objectGetOption;
			if (options == null)
			{
				objectGetOption = new ObjectGetOptions();
			}
			else
			{
				objectGetOption = new ObjectGetOptions(options.context, options.timeout, options.UseAmendedQualifiers);
			}
			if (handler == null)
			{
				if (options != null)
				{
					objectGetOption.IdentifierChanged += new IdentifierChangedEventHandler(options.HandleIdentifierChange);
				}
			}
			else
			{
				objectGetOption.IdentifierChanged += handler;
			}
			return objectGetOption;
		}
Exemple #17
0
        /// <summary>
        /// 在远程目标机器上创建一个注册表键值
        /// </summary>
        /// <param name="connectionScope">ManagementScope</param>
        /// <param name="machineName">目标机器IP</param>
        /// <param name="BaseKey">注册表分支名</param>
        /// <param name="key">主键名称</param>
        /// <param name="valueName">键值名称</param>
        /// <param name="value">键值</param>
        /// <returns>创建成功则返回0</returns>
        public static int CreateRemoteValue(ManagementScope connectionScope,
                                    string machineName,
                                    RootKey BaseKey,
                                    string key,
                                    string valueName,
                                    string value)
        {
            try
            {
                ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                connectionScope.Path = new ManagementPath(@"\\" + machineName + @"\root\DEFAULT:StdRegProv");
                connectionScope.Connect();
                ManagementClass registryTask = new ManagementClass(connectionScope,
                               new ManagementPath(@"DEFAULT:StdRegProv"), objectGetOptions);
                ManagementBaseObject methodParams = registryTask.GetMethodParameters("SetStringValue");

                methodParams["hDefKey"] = BaseKey;
                methodParams["sSubKeyName"] = key;
                methodParams["sValue"] = value;
                methodParams["sValueName"] = valueName;

                ManagementBaseObject exitCode = registryTask.InvokeMethod("SetStringValue",
                                                                         methodParams, null);

                Wmilog.LogInfoWithLevel("in CreateRemoteValue:" + exitCode.ToString(), Log_LoggingLevel.Admin);
            }
            catch (ManagementException e)
            {
                Wmilog.LogInfoWithLevel("in CreateRemoteValue(ManagementException):" + e.Message, Log_LoggingLevel.Admin);
                return -1;
            }
            Wmilog.LogInfoWithLevel("注册表键值写入成功!", Log_LoggingLevel.Admin);
            return 0;
        }
Exemple #18
0
        public static string InsertAT(  string srv, string usr, string pwd, 
                                        string inCMD, string inRPT, string inDOW, string inDOM, string inSTM)
        {
            try
            {
                MPSfwk.Model.Server s = new MPSfwk.Model.Server();
                s.IPHOST = srv;
                s.USUARIO = usr;
                s.SENHA = pwd;
                string strJobId = "";
                ManagementScope ms = scopeMgmt(false, s);
                ObjectGetOptions objectGetOptions = new ObjectGetOptions();
                ManagementPath managementPath = new ManagementPath("Win32_ScheduledJob");
                ManagementClass processClass = new ManagementClass(ms, managementPath, objectGetOptions);
                ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
                inParams["Command"] = inCMD;
                inParams["InteractWithDesktop"] = "False";
                inParams["RunRepeatedly"] = inRPT;
                inParams["DaysOfMonth"] = inDOM;
                inParams["DaysOfWeek"] = inDOW;
                inParams["StartTime"] = inSTM + "00.000000-180";
                ManagementBaseObject outParams =
                        processClass.InvokeMethod("Create", inParams, null);

                strJobId = outParams["JobId"].ToString();

                return "Novo JobId (" + strJobId + ") criado com sucesso!";
            }
            catch (UnauthorizedAccessException uex)
            {
                return "Ocorreu um erro: " + uex.Message;
            }
            catch (ManagementException mex)
            {
                return "Ocorreu um erro: " + mex.Message;
            }
        }
 public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
		public ManagementObject (string scopeString, string pathString, ObjectGetOptions options)
		{
		}
Exemple #21
0
 public RegistryKeyChangeEvent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
 public BcdStringElement(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
		public ManagementObject (string path, ObjectGetOptions options)
		{
		}
 public EthernetPortAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
Exemple #25
0
 public VLANEndpointSettingData(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);
 }
 public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
Exemple #28
0
 public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
 public NetworkAdapterConfiguration(ManagementScope mgmtScope, ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
 public KvpExchangeComponentSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
        /// <summary>
        /// Handles the event to draw the contents of the class list combo box items.
        /// </summary>
        private void ClassList_DrawItem(object sender, DrawItemEventArgs e)
        {
            string text = this.ClassList.GetItemText(this.ClassList.Items[e.Index]);

            try
            {
                ObjectGetOptions op = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                ManagementClass mc = new ManagementClass(this.NamespaceList.Text,
                    this.ClassList.GetItemText(this.ClassList.Items[e.Index]), op);
                mc.Options.UseAmendedQualifiers = true;

                foreach (QualifierData qualifierObject in
                    mc.Qualifiers)
                {
                    // Gets the class description.
                    if (qualifierObject.Name.ToLower().Equals("description"))
                    {
                        if (qualifierObject.Value.ToString() != String.Empty)
                        {
                            text = text + Environment.NewLine;

                            int length = 0;
                            foreach (string word in qualifierObject.Value.ToString().Split(" ".ToCharArray()))
                            {
                                if (length < 70)
                                {
                                    text = text + word + " ";
                                    length = length + word.Length;
                                }
                                else
                                {
                                    length = 0;
                                    text = text + word + Environment.NewLine;
                                }
                            }
                        }
                    }
                }
            }
            catch (ManagementException)
            {
            }

            e.DrawBackground();

            using (SolidBrush br = new SolidBrush(e.ForeColor))
            {
                e.Graphics.DrawString(text, e.Font, br, e.Bounds);
            }

            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                int x = e.Bounds.Right;
                int y = this.ClassList.PointToClient(Cursor.Position).Y - e.Bounds.Height;

                this.QueryControlToolTip.Show(text, this.ClassList, x, y);
            }

            else
            {
                this.QueryControlToolTip.Hide(this.ClassList);
            }

            e.DrawFocusRectangle();
        }
Exemple #32
0
 public WmiMonitorBrightness(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
 public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
Exemple #34
0
 public ProcessorSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
Exemple #35
0
 public SendHandler2(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
 public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
		public ManagementObject (ManagementScope scope, ManagementPath path, ObjectGetOptions options)
		{
		}
 public Desktop(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
        public DeploymentResult Execute()
        {
            var result = new DeploymentResult();
            var connOptions = new ConnectionOptions
                              {
                                  Impersonation = ImpersonationLevel.Impersonate, EnablePrivileges = true
                              };

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

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

            var inParams = processClass.GetMethodParameters("Create");

            inParams["CommandLine"] = Command;
            var outParams = processClass.InvokeMethod("Create", inParams, null);

            int returnVal = Convert.ToInt32(outParams["returnValue"]);

            if (returnVal != 0)
                result.AddError(_status[returnVal]);
            //TODO: how to tell DK to stop executing?

            return result;
        }
Exemple #40
0
 /// <summary>
 /// Get a ManagementObject with specified path and ObjectGetOptions.
 /// </summary>
 /// <param name="path">The path to return the object from.</param>
 /// <param name="oGetOptions">The options to use.</param>
 /// <returns>Returns a ManagementObject.</returns>
 public ManagementObject GetObject(string path, ObjectGetOptions oGetOptions)
 {
     ManagementObject result = new ManagementObject(mScope, new ManagementPath(path), oGetOptions);
     result.Get();
     return result;
 }
Exemple #41
0
        public static DataTable GroupMembers(string srv, string usr, string pwd)
        {
            StringBuilder result = new StringBuilder();
            try
            {
                //
                MPSfwk.Model.Server s = new MPSfwk.Model.Server();
                s.IPHOST = srv;
                s.USUARIO = usr;
                s.SENHA = pwd;
                ManagementScope ms = scopeMgmt(false, s);
                ObjectGetOptions objectGetOptions = new ObjectGetOptions();
                //
                string targethost = "";
                string groupname = "";
                string aux_qry = "";
                if ((srv.IndexOf(".") == -1) && (srv.ToUpper() != "LOCALHOST"))
                {   aux_qry = "select * from Win32_Group Where Domain = '" + srv + "'"; }
                else
                { aux_qry = "select * from Win32_Group Where LocalAccount = True"; }
                //
                //MPS teste - 10/out
                //
                Console.WriteLine("DEBUG - aux_qry = " + aux_qry);
                //
                DataTable dt_aux = dtlistaClasse("Win32_Group",
                                                    aux_qry,
                                                    srv,
                                                    usr,
                                                    pwd);
                //
                //Cria tabela para preencher os campos
                DataTable dt1 = new DataTable();
                dt1.TableName = "GroupMembers";
                dt1.Columns.Add("Domain");
                dt1.Columns.Add("Group Name");
                dt1.Columns.Add("Users");
                //
                foreach (DataRow drow in dt_aux.Rows)
                {
                    //
                    DataRow dr = dt1.NewRow();
                    //
                    targethost = drow["Domain"].ToString();
                    groupname = drow["Name"].ToString();

                    StringBuilder qs = new StringBuilder();
                    qs.Append("SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = \"Win32_Group.Domain='");
                    qs.Append(targethost);
                    qs.Append("',Name='");
                    qs.Append(groupname);
                    qs.AppendLine("'\"");
                    ObjectQuery query = new ObjectQuery(qs.ToString());
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);
                    ManagementObjectCollection queryCollection = searcher.Get();
                    foreach (ManagementObject m in queryCollection)
                    {
                        ManagementPath path = new ManagementPath(m["PartComponent"].ToString());
                        {
                            String[] names = path.RelativePath.Split(',');
                            result.Append(names[0].Substring(names[0].IndexOf("=") + 1).Replace("\"", " ").Trim() + "\\");
                            result.AppendLine(names[1].Substring(names[1].IndexOf("=") + 1).Replace("\"", " ").Trim() + " ; ");
                        }
                    }
                    //Console.WriteLine("Domain =  " + targethost + " Name = " + groupname + " Users = " + result.ToString());
                    dr["Domain"] = targethost;
                    dr["Group Name"] = groupname;
                    dr["Users"] = result.ToString();
                    dt1.Rows.Add(dr);
                    //
                    result = new StringBuilder();

                }
                return dt1;
                //
            }
            catch (Exception e)
            {
                Console.WriteLine("|!| GroupMembers Error - " + e.Message);
                return null;
            }
        }
Exemple #42
0
 private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam)
 {
     if (((path != null) &&
          (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)))
     {
         return(true);
     }
     else
     {
         return(CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)));
     }
 }
        private void CreateRestorePoint(string description)
        {
            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"] = description;
            oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS
            oInParams["EventType"] = 100;

            ManagementBaseObject oOutParams =
                oProcess.InvokeMethod("CreateRestorePoint", oInParams, null);
        }
Exemple #44
0
 public EnvironmentWmi(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
Exemple #45
0
        /// <summary>
        /// 创建远程目录
        /// </summary>
        /// <param name="scope">ManagementScope Instance</param>
        /// <param name="DirectoryName">要建立的目录名</param>
        /// <param name="CurrentDirectory">根目录所在位置,缺省为C:\</param>
        /// <returns>0表示建立成功,-1表示建立失败</returns>
        public static int CreateRemoteDirectory(ManagementScope scope, string DirectoryName, string CurrentDirectory)
        {
            try
            {
                string currentDirectory = CurrentDirectory;
                if (String.IsNullOrEmpty(CurrentDirectory))
                {
                    currentDirectory = @"C:\";
                }
                ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                ManagementPath managementPath = new ManagementPath("Win32_Process");

                ManagementClass processBatch = new ManagementClass(scope, managementPath, objectGetOptions);
                ManagementBaseObject inParams = processBatch.GetMethodParameters("Create");

                inParams["CommandLine"] = @"cmd /CMd " + DirectoryName;
                inParams["CurrentDirectory"] = currentDirectory;

                ManagementBaseObject outParams = null;
                outParams = processBatch.InvokeMethod("Create", inParams, null);

                Wmilog.LogInfoWithLevel("Excute CreateRemoteDirectory:" + outParams.ToString(), Log_LoggingLevel.Admin);
            }
            catch (Exception ex)
            {
                Wmilog.LogInfoWithLevel("in CreateRemoteDirectory Exception:" + ex.Message, Log_LoggingLevel.Admin);
                return -1;
            }
            Wmilog.LogInfoWithLevel("建远程目录成功!", Log_LoggingLevel.Admin);
            return 0;
        }
Exemple #46
0
 public ManagementClass(ManagementScope scope, ManagementPath path, ObjectGetOptions options)
 {
     throw new NotImplementedException();
 }
        //-------------------------------------------------------------------------
        // Populates the query tab's property list with properties from
        // the class in the class list.
        //-------------------------------------------------------------------------
        private void AddPropertiesToList(object o)
        {
            int propertyCount = 0;
            this.PropertyStatus.Text = "Searching...";

            this.PropertyList.Items.Clear();

            try
            {
                // Gets the property qualifiers.
                ObjectGetOptions op = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);

                ManagementClass mc = new ManagementClass(this.NamespaceList.Text,
                    this.ClassList.Text, op);
                mc.Options.UseAmendedQualifiers = true;

                foreach (PropertyData dataObject in
                    mc.Properties)
                {
                    if (!this.PropertyList.Items.Contains(dataObject.Name))
                    {
                        this.PropertyList.Items.Add(
                            dataObject.Name);
                    }
                    propertyCount++;
                }

                this.PropertyStatus.Text =
                    propertyCount + " properties found.";
            }
            catch (ManagementException ex)
            {
                this.PropertyStatus.Text = ex.Message;
            }
        }
Exemple #48
0
 private void InitializeObject(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions)
 {
     Initialize();
     if ((path != null))
     {
         if ((CheckIfProperClass(mgmtScope, path, getOptions) != true))
         {
             throw new ArgumentException("Class name does not match.");
         }
     }
     _privateLateBoundObject = new ManagementObject(mgmtScope, path, getOptions);
     _privateSystemProperties = new ManagementSystemProperties(_privateLateBoundObject);
     _curObj = _privateLateBoundObject;
 }
        /// <summary>
        /// Sets the tool tip for items in the property list.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PropertyList_MouseMove(object sender, MouseEventArgs e)
        {
            string text = "";

            int index = this.PropertyList.IndexFromPoint(e.Location);

            if (index >= 0 && index < this.PropertyList.Items.Count)
            {
                text = this.PropertyList.Items[index].ToString();

                try
                {
                    ObjectGetOptions op = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
                    ManagementClass mc = new ManagementClass(this.NamespaceList.Text,
                        this.ClassList.GetItemText(this.ClassList.Text), op);

                    mc.Options.UseAmendedQualifiers = true;

                    foreach (QualifierData qualifierObject in
                        mc.Properties[text].Qualifiers)
                    {
                        // Gets the class description.
                        if (qualifierObject.Name.ToLower().Equals("description"))
                        {
                            if (qualifierObject.Value.ToString() != String.Empty)
                            {
                                text = text + Environment.NewLine;

                                int length = 0;
                                foreach (string word in qualifierObject.Value.ToString().Split(" ".ToCharArray()))
                                {
                                    if (length < 70)
                                    {
                                        text = text + word + " ";
                                        length = length + word.Length;
                                    }
                                    else
                                    {
                                        length = 0;
                                        text = text + word + Environment.NewLine;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (ManagementException)
                {
                }

                if (QueryControlToolTip.GetToolTip(this.PropertyList) != text)
                {
                    this.QueryControlToolTip.SetToolTip(this.PropertyList, text);
                }
            }
            else
            {
                this.QueryControlToolTip.Hide(this.PropertyList);
            }
        }
Exemple #50
0
 public ComputerSystem(ManagementPath path, ObjectGetOptions getOptions)
 {
     InitializeObject(null, path, getOptions);
 }
 public VirtualHardDiskSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
Exemple #52
0
 public ComputerSystem(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions)
 {
     InitializeObject(mgmtScope, path, getOptions);
 }
        } // end _DoInstall()


        // This can throw a Win32Exception, a ManagementException, or an
        // OperationCanceledException.
        private int _RunCommand( string command, bool instaKill, ICauPluginCallbackBase callback )
        {
            int exitCode = -1;
            int processId = 0;
            string username = null;
            SecureString password = null;
            if( null != m_cred )
            {
                username = m_cred.UserName;
                password = m_cred.Password;
            }

            object gate = new object();

            ConnectionOptions co = new ConnectionOptions( null,        // locale
                                                          username,
                                                          password,
                                                          null,        // authority
                                                          ImpersonationLevel.Impersonate,
                                                          AuthenticationLevel.PacketPrivacy,
                                                          true,        // enable privileges
                                                          null,        // context
                                                          TimeSpan.Zero );
            string path = String.Format( CultureInfo.InvariantCulture, @"\\{0}\root\cimv2", m_machine );
            ManagementScope scope = new ManagementScope( path, co );
            ObjectGetOptions objGetOptions = new ObjectGetOptions();

            scope.Connect();

            // We start the query before launching the process to prevent any possibility
            // of a timing or PID recycling problem.
            WqlEventQuery query = new WqlEventQuery( "Win32_ProcessStopTrace" );
            EventWatcherOptions watcherOptions = new EventWatcherOptions( null, TimeSpan.MaxValue, 1 );
            using( ManagementEventWatcher watcher = new ManagementEventWatcher( scope, query, watcherOptions ) )
            {
                watcher.EventArrived += (sender, arg) =>
                {
                    int stoppedProcId = (int) (uint) arg.NewEvent[ "ProcessID" ];
                    if( stoppedProcId == processId )
                    {
                        exitCode = (int) (uint) arg.NewEvent[ "ExitStatus" ];

                        if( null != callback )
                        {
                            callback.WriteVerbose( String.Format( CultureInfo.CurrentCulture,
                                                                  "Process ID {0} on {1} exited with code: {2}",
                                                                  processId,
                                                                  m_machine,
                                                                  exitCode ) );
                        }

                        lock( gate )
                        {
                            Monitor.PulseAll( gate );
                        }
                    }
                };

                watcher.Start();

                int timeout = Timeout.Infinite;
                ManagementPath mPath = new ManagementPath( "Win32_Process" );
                using( ManagementClass mc = new ManagementClass( scope, mPath, objGetOptions ) )
                using( ManagementBaseObject inParams = mc.GetMethodParameters( "Create" ) )
                {
                    inParams[ "CommandLine" ] = command;
                    using( ManagementBaseObject outParams = mc.InvokeMethod( "Create", inParams, null ) )
                    {
                        int err = (int) (uint) outParams[ "returnValue" ];
                        if( 0 != err )
                        {
                            throw new Win32Exception( err );
                        }
                        processId = (int) (uint) outParams[ "processId" ];
                        Debug.Assert( processId > 0 );
                    }
                }

                if( null != callback )
                {
                    callback.WriteVerbose( String.Format( CultureInfo.CurrentCulture,
                                                          "Process launched on {0} with ID: {1}",
                                                          m_machine,
                                                          processId ) );
                }

                // If instaKill is true, we are trying to test our ability to receive
                // Win32_ProcessStopTrace events, so kill the process immediately.
                if( instaKill )
                {
                    SelectQuery killQuery = new SelectQuery( "SELECT * FROM Win32_Process WHERE ProcessId = " + processId );
                    using( ManagementObjectSearcher searcher = new ManagementObjectSearcher( scope, killQuery ) )
                    {
                        foreach( ManagementObject obj in searcher.Get() )
                        {
                            obj.InvokeMethod( "Terminate", new object[] { (uint) c_TestWmiExitCode } );
                            obj.Dispose();
                        }
                    }

                    // If we don't receive the Win32_ProcessStopTrace event within 10
                    // seconds, we'll assume it's not coming. In that case, there's
                    // probably a firewall problem blocking WMI.
                    timeout = 10000;
                }

                // Wait until the process exits (or we get canceled).
                lock( gate )
                {
                    // If we get canceled, we stop waiting for the remote process to
                    // finish and just leave it running.
                    using( m_cancelToken.Register( () => { lock( gate ) { Monitor.PulseAll( gate ); } } ) )
                    {
                        if( !Monitor.Wait( gate, timeout ) )
                        {
                            Debug.Assert( instaKill, "This call should not time out unless we are in the instaKill scenario." );
                            throw new ClusterUpdateException( "The Fabrikam CAU plugin is able to create a process on cluster node \"{0}\" using WMI, but is not able to receive process lifetime events. Check the firewalls on both this computer and the target node and ensure that the appropriate WMI rules are enabled.",
                                                              "WmiTestReceiveEventFailed",
                                                              ErrorCategory.ResourceUnavailable );
                        }
                    }
                }

                watcher.Stop();
                m_cancelToken.ThrowIfCancellationRequested();
            }

            return exitCode;
        } // end _RunCommand()
 public SummaryInformation(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
Exemple #55
0
 private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     Initialize();
     if ((path != null))
     {
         if ((CheckIfProperClass(mgmtScope, path, getOptions) != true))
         {
             throw new System.ArgumentException("Class name does not match.");
         }
     }
     PrivateLateBoundObject  = new System.Management.ManagementObject(mgmtScope, path, getOptions);
     PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject);
     curObj = PrivateLateBoundObject;
 }
 public BcdObject(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }
Exemple #57
0
 public HostInstanceSetting(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(mgmtScope, path, getOptions);
 }
Exemple #58
0
 public ManagementClass(string scope, string path, ObjectGetOptions options)
 {
     throw new NotImplementedException();
 }
Exemple #59
0
 /// <summary>
 /// Gets a ManagementClass given the class name and ObjectGetOPtions.
 /// </summary>
 /// <param name="sClassName">The classname to return.</param>
 /// <param name="oGetOptions">The objectgetoptions to use.</param>
 /// <returns>Returns a ManagementClass</returns>
 public ManagementClass GetClass(string sClassName, ObjectGetOptions oGetOptions)
 {
     ManagementClass result = new ManagementClass(mScope, new ManagementPath(sClassName), oGetOptions);
     return result;
 }
 public RegistryTreeChangeEvent(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions)
 {
     this.InitializeObject(null, path, getOptions);
 }