Ejemplo n.º 1
0
 private static void Win32_SharesSearcher()
 {
     SelectQuery query = new SelectQuery("select * from Win32_Share where Name=\"" + sharename + "\"");
     using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
     {
         foreach (ManagementObject mo in searcher.Get())
         {
             foreach (PropertyData prop in mo.Properties)
             {
                 form.textBox1.AppendText(prop.Name + " = " + mo[prop.Name] + Environment.NewLine);                    }
                 //form.textBox1.AppendText(string.Format("Win32ShareName: {0} Description {1} Path {2} ", mo.Properties["Name"].Value, mo.Properties["Description"].Value, mo.Properties["Path"].Value) + Environment.NewLine);
         }
     }
     ManagementObject winShareP = new ManagementObject("root\\CIMV2", "Win32_Share.Name=\"" + sharename + "\"", null);
     ManagementBaseObject outParams = winShareP.InvokeMethod("GetAccessMask", null, null);
     form.textBox1.AppendText(String.Format("access Mask = {0:x}", outParams["ReturnValue"]) + Environment.NewLine);
     ManagementBaseObject inParams = winShareP.GetMethodParameters("SetShareInfo");
     form.textBox1.AppendText("SetShareInfor in parameters" + Environment.NewLine);
     foreach (PropertyData prop in inParams.Properties)
     {
         form.textBox1.AppendText(String.Format("PROP = {0}, TYPE = {1} ", prop.Name, prop.Type.ToString()) + Environment.NewLine);
     }
     Object access = inParams.GetPropertyValue("Access");
     //Stopped development here because ShareAFolder project exists. The rest of the development is there
     //Maybe should copy Sahare a Folder content to here at some point
 }
Ejemplo n.º 2
0
        /// <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;
        }
        public string SetHostname(string hostname)
        {
            var oldName = Environment.MachineName;
            _logger.Log("Old host name: " + oldName);
            _logger.Log("New host name: " + hostname);
            if (string.IsNullOrEmpty(hostname) || oldName.Equals(hostname, StringComparison.InvariantCultureIgnoreCase))
                return 0.ToString();

            using (var cs = new ManagementObject(@"Win32_Computersystem.Name='" + oldName + "'"))
            {
                cs.Get();
                var inParams = cs.GetMethodParameters("Rename");
                inParams.SetPropertyValue("Name", hostname);
                var methodOptions = new InvokeMethodOptions(null, TimeSpan.MaxValue);
                var outParams = cs.InvokeMethod("Rename", inParams, methodOptions);
                if (outParams == null)
                    return 1.ToString();

                var renameResult = Convert.ToString(outParams.Properties["ReturnValue"].Value);
                //Restart in 10 secs because we want finish current execution and write response back to Xenstore.
                if ("0".Equals(renameResult))
                    Process.Start(@"shutdown.exe", @"/r /t 10 /f /d p:2:4");
                return renameResult;
            }
        }
 /// <summary>
 /// 设置服务与桌面交互,在serviceInstaller1的AfterInstall事件中使用
 /// </summary>
 /// <param name="serviceName">服务名称</param>
 private void SetServiceDesktopInsteract(string serviceName)
 {
     ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", serviceName));
     ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
     changeMethod["DesktopInteract"] = true;
     ManagementBaseObject utParam = wmiService.InvokeMethod("Change", changeMethod,null);
 }
Ejemplo n.º 5
0
        protected override void OnCommitted(IDictionary savedState)
        {
            base.OnCommitted (savedState);

            // Setting the "Allow Interact with Desktop" option for this service.
            ConnectionOptions connOpt = new ConnectionOptions();
            connOpt.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope mgmtScope = new ManagementScope(@"root\CIMv2", connOpt);
            mgmtScope.Connect();
            ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + ReflectorMgr.ReflectorServiceName + "'");
            ManagementBaseObject inParam = wmiService.GetMethodParameters("Change");
            inParam["DesktopInteract"] = true;
            ManagementBaseObject outParam = wmiService.InvokeMethod("Change", inParam, null);

            #region Start the reflector service immediately
            try
            {
                ServiceController sc = new ServiceController("ConferenceXP Reflector Service");
                sc.Start();
            }
            catch (Exception ex)
            {
                // Don't except - that would cause a rollback.  Instead, just tell the user.
                RtlAwareMessageBox.Show(null, string.Format(CultureInfo.CurrentCulture, Strings.ServiceStartFailureText, 
                    ex.ToString()), Strings.ServiceStartFailureTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning, 
                    MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);
            }
            #endregion
        }
Ejemplo n.º 6
0
        public override void Install(System.Collections.IDictionary savedState)
        {
            try
            {
                base.Install(savedState);

                // Turn on "Allow service to interact with desktop".
                // (Note: A published technique to do this by setting a bit in the service's Type registry value (0x100) does not turn this on, so do as follows.)
                // This will let the NotifyIcon appear in the sys tray (with balloon at start-up), but not its context menu.
                ConnectionOptions options = new ConnectionOptions();
                options.Impersonation = ImpersonationLevel.Impersonate;
                ManagementScope scope = new ManagementScope(@"root\CIMv2", options); // Common Information Model, version 2.
                ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + this.serviceInstaller.ServiceName + "'");
                ManagementBaseObject inParameters = wmiService.GetMethodParameters("Change");
                inParameters["DesktopInteract"] = true;
                ManagementBaseObject outParameters = wmiService.InvokeMethod("Change", inParameters, null);
            }
            catch (Exception e)
            {
                string licenseKey = "";
                string licenseName = "";
                try
                {
                    licenseKey = Properties.Settings.Default.LicenseKey;
                    licenseName = Properties.Settings.Default.LicenseName;
                }
                catch { }

                Service.Services.LoggingService.AddLogEntry(WOSI.CallButler.ManagementInterface.LogLevel.ErrorsOnly, Utils.ErrorUtils.FormatErrorString(e), true);
                CallButler.ExceptionManagement.ErrorCaptureUtils.SendError(e, licenseKey, licenseName, "");
            }
        }
Ejemplo n.º 7
0
 public void SetNetCfg(string strIP, string strSubmask, string strGateway, string strDNS1, string strDNS2)
 {
     // 建立 ManagementObject 物件 ( Scope , Path , options )
     objCls = new ManagementObject(strNS, strCls + ".INDEX=" + strIndex, null);
     ManagementBaseObject objInPara; // 宣告管理物件類別的基本類別
     objInPara = objCls.GetMethodParameters("EnableStatic");
     objInPara["IPAddress"] = new string[] { strIP }; // 設定 "IP" 屬性
     objInPara["SubnetMask"] = new string[] { strSubmask }; // 設定 "子網路遮罩" 屬性
     objCls.InvokeMethod("EnableStatic", objInPara, null);
     objInPara = objCls.GetMethodParameters("SetGateways");
     objInPara["DefaultIPGateway"] = new string[] { strGateway }; // 設定 "Gateway" 屬性
     objCls.InvokeMethod("SetGateways", objInPara, null);
     objInPara = objCls.GetMethodParameters("SetDNSServerSearchOrder");
     objInPara["DNSServerSearchOrder"] = new string[] { strDNS1, strDNS2 }; // 設定 "DNS" 屬性
     objCls.InvokeMethod("SetDNSServerSearchOrder", objInPara, null);
     // GetMethodParameters 方法 : 用來取得 SetDNSServerSearchOrder 參數清單。
     // InvokeMethod 方法 : 在物件上叫用方法。
 }
Ejemplo n.º 8
0
        private void SetServiceDesktopInsteract(string serviceName) {
            ConnectionOptions coOptions = new ConnectionOptions();
            coOptions.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope mgmtScope = new System.Management.ManagementScope(@"root\CIMV2", coOptions);
            mgmtScope.Connect();

            ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", serviceName));
            ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
            changeMethod["DesktopInteract"] = true;
            ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", changeMethod, null);
        }
Ejemplo n.º 9
0
        private void button2_Click(object sender, EventArgs e)
        {
            string AccountName = textBox1.Text,
                newNameForAccount = textBox2.Text;

            ManagementObject theInstance = new ManagementObject("root\\CIMv2", "Win32_UserAccount.Domain='" + Environment.MachineName + "',Name='" + AccountName + "'", null);

            ManagementBaseObject inputParams = theInstance.GetMethodParameters("Rename");
            inputParams.SetPropertyValue("Name", newNameForAccount);
            ManagementBaseObject outParams = theInstance.InvokeMethod("Rename", inputParams, null);
            button2.Hide();
        }
Ejemplo n.º 10
0
        private void serviceInstaller1_Committed(object sender, InstallEventArgs e)
        {
            ConnectionOptions options = new ConnectionOptions();
            options.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope scope = new ManagementScope(@"root\CIMV2", options);
            scope.Connect();

            ManagementObject wmi = new ManagementObject("Win32_Service.Name='" + serviceInstaller1.ServiceName + "'");
            ManagementBaseObject inParam = wmi.GetMethodParameters("Change");
            inParam["DesktopInteract"] = true;
            ManagementBaseObject outParam = wmi.InvokeMethod("Change", inParam, null);
        }
Ejemplo n.º 11
0
        public IisWebSite CreateWebSite(string serverComment, IEnumerable<IisWebSiteBindingDetails> bindings, string documentRoot)
        {
            var iis = new ManagementObject(scope, new ManagementPath("IIsWebService='W3SVC'"), null);

            ManagementBaseObject createNewSiteArgs = iis.GetMethodParameters("CreateNewSite");
            createNewSiteArgs["ServerComment"] = serverComment;
            createNewSiteArgs["ServerBindings"] = bindings.Select(b => CreateBinding(b)).ToArray();
            createNewSiteArgs["PathOfRootVirtualDir"] = documentRoot;

            var result = iis.InvokeMethod("CreateNewSite", createNewSiteArgs, null);

            var id = (string) result["ReturnValue"];
            return new IisWebSite(scope, id);
        }
        public static uint SetComputerName(String Name)
        {
            uint ret;
            ManagementObject ob = new ManagementObject();
            using (ManagementObject wmiObject = new ManagementObject(new ManagementPath(String.Format("Win32_ComputerSystem.Name='{0}'", System.Environment.MachineName))))
            {
                ManagementBaseObject inputArgs = wmiObject.GetMethodParameters("Rename");
                inputArgs["Name"] = Name;

                ManagementBaseObject outParams = wmiObject.InvokeMethod("Rename", inputArgs, null);
                ret = (uint)(outParams.Properties["ReturnValue"].Value);
            }
            return ret;
        }
Ejemplo n.º 13
0
 public static void SetBrightness(int value)
 {
     ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM WmiMonitorBrightness");
     string instance = "";
     foreach (ManagementObject queryObj in searcher.Get())
     {
         instance = queryObj.GetPropertyValue("InstanceName").ToString();
     }
     ManagementObject classInstance = new ManagementObject(@"root\WMI", @"WmiMonitorBrightnessMethods.InstanceName='" + instance + "'", null);
     ManagementBaseObject inParams = classInstance.GetMethodParameters("WmiSetBrightness");
     inParams["Brightness"] = value;
     inParams["Timeout"] = 5000;
     ManagementBaseObject outParams = classInstance.InvokeMethod("WmiSetBrightness", inParams, null);
 }
Ejemplo n.º 14
0
 protected override void OnAfterInstall(IDictionary savedState)
 {
     try
     {
         System.Management.ManagementObject myService = new System.Management.ManagementObject(
             string.Format("Win32_Service.Name='{0}'", this.serviceInstaller1.ServiceName));
         System.Management.ManagementBaseObject changeMethod = myService.GetMethodParameters("Change");
         changeMethod["DesktopInteract"] = true;
         System.Management.ManagementBaseObject OutParam = myService.InvokeMethod("Change", changeMethod, null);
     }
     catch (Exception)
     {
     }
     base.OnAfterInstall(savedState);
 }
Ejemplo n.º 15
0
 // add pc to domain
 public static bool addToDomain(string userName, string password, string domain)
 {
     using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")))
     {
         try
         {
             ManagementBaseObject inParams = wmiObject.GetMethodParameters("JoinDomainorWorkgroup");
             inParams["Name"] = domain;
             inParams["Password"] = password;
             inParams["UserName"] = userName;
             inParams["FJoinOptions"] = 3;
             ManagementBaseObject outParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);
             if (!outParams["ReturnValue"].ToString().Equals("0")) return false;
             return true;
         }
         catch
         {
             return false;
         }
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// This will restart the Pocess
        /// </summary>
        /// <returns>This will return True if the Process is successfully restarted. If the Process isn't running, or if there was an error in restarting it then it will return False.</returns>
        public static bool RestartProcess(int PID)
        {
            string ProcessName = "";
            try
            {
                ManagementObject classInstance = new ManagementObject("root\\CIMV2", "Win32_Process.Handle='"+PID+"'", null);
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT Name FROM Win32_Process WHERE ProcessId =" + PID  + @"");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    ProcessName = queryObj["Name"].ToString().Trim();
                }

                // Obtain in-parameters for the method
                ManagementBaseObject inParams = classInstance.GetMethodParameters("Terminate");

                // Add the input parameters.

                // Execute the method and obtain the return values.
                ManagementBaseObject outParams = classInstance.InvokeMethod("Terminate", inParams, null);

                // List outParams
                Console.WriteLine("Out parameters:");
                Console.WriteLine("ReturnValue: " + outParams["ReturnValue"]);
                if (int.Parse(outParams["ReturnValue"].ToString().Trim()) != 0)
                {
                    return false;
                }
                else
                {
                    return StartProcess(ProcessName);
                }
            }
            catch (ManagementException err)
            {
                Console.WriteLine("An error occurred while trying to execute the WMI method: " + err.Message);
                return false;
            }
        }
Ejemplo n.º 17
0
        public static bool SetMachineName(string Name)
        {
            String RegLocComputerName = @"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName";
            try
            {
                string compPath = "Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'";
                using (ManagementObject mo = new ManagementObject(new ManagementPath(compPath)))
                {
                    ManagementBaseObject inputArgs = mo.GetMethodParameters("Rename");
                    inputArgs["Name"] = Name;
                    ManagementBaseObject output = mo.InvokeMethod("Rename", inputArgs, null);
                    uint retValue = (uint)Convert.ChangeType(output.Properties["ReturnValue"].Value, typeof(uint));
                    if (retValue != 0)
                    {
                        LogHelper.WriteLog("Computer could not be changed due to unknown reason.");
                    }
                }

                RegistryKey ComputerName = Registry.LocalMachine.OpenSubKey(RegLocComputerName);
                if (ComputerName == null)
                {
                    LogHelper.WriteLog("Registry location '" + RegLocComputerName + "' is not readable.");
                }
                if (((String)ComputerName.GetValue("ComputerName")) != Name)
                {
                    LogHelper.WriteLog("The computer name was set by WMI but was not updated in the registry location: '" + RegLocComputerName + "'");
                }
                LogHelper.WriteLog("更改计算机名:"+Name);
                ComputerName.Close();
                ComputerName.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("出现错误", ex);
                return false;
            }
            return true;
        }
        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]");
Ejemplo n.º 19
0
        private static void UpdateHostname()
        {
            string newHostName = Config.AgentId;

            if (Environment.MachineName != newHostName)
            {
                Logger.Info("Updating hostname to :" + Config.AgentId);

                string w32comp = "Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'";
                using (ManagementObject computer = new ManagementObject(new ManagementPath(w32comp)))
                {
                    ManagementBaseObject param = computer.GetMethodParameters("Rename");
                    param["Name"] = newHostName;
                    ManagementBaseObject outParam = computer.InvokeMethod("Rename", param, null);
                    int returnCode = (int)(uint)outParam.Properties["returnValue"].Value;
                    if (returnCode != 0)
                    {
                        Logger.Error("Could not update hostname " + returnCode);
                    }
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Stop the Process.
        /// </summary>
        /// <returns>It will return True if the Process is successfully stopped. If the Process isn't running, or there was an error when stopping it, then it will return False.</returns>
        public static bool StopProcess(int PID)
        {
            try
            {
                ManagementObject classInstance = new ManagementObject("root\\CIMV2", "Win32_Process.Handle='" + PID + "'", null);

                // Obtain in-parameters for the method
                ManagementBaseObject inParams = classInstance.GetMethodParameters("Terminate");

                // Add the input parameters.

                // Execute the method and obtain the return values.
                ManagementBaseObject outParams = classInstance.InvokeMethod("Terminate", inParams, null);

                // List outParams
                Console.WriteLine("Out parameters:");
                Console.WriteLine("ReturnValue: " + outParams["ReturnValue"]);
                if (int.Parse(outParams["ReturnValue"].ToString().Trim()) != 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (ManagementException err)
            {
                Console.WriteLine("An error occurred while trying to execute the WMI method: " + err.Message);
                return false;
            }
        }
Ejemplo n.º 21
0
        private void ExecuteWmi()
        {
            this.GetManagementScope(this.Namespace.Get(this.ActivityContext));
            string managementPath = this.Class.Get(this.ActivityContext);
            if (!string.IsNullOrEmpty(this.Instance.Get(this.ActivityContext)))
            {
                managementPath += "." + this.Instance.Get(this.ActivityContext);

                using (var classInstance = new ManagementObject(this.Scope, new ManagementPath(managementPath), null))
                {
                    // Obtain in-parameters for the method
                    ManagementBaseObject inParams = classInstance.GetMethodParameters(this.Method.Get(this.ActivityContext));
                    this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Method: {0}", this.Method.Get(this.ActivityContext)), BuildMessageImportance.Low);

                    if (this.MethodParameters != null)
                    {
                        // Add the input parameters.
                        foreach (string[] data in this.MethodParameters.Get(this.ActivityContext).Select(param => param.Split(new[] { "#~#" }, StringSplitOptions.RemoveEmptyEntries)))
                        {
                            this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Param: {0}. Value: {1}", data[0], data[1]), BuildMessageImportance.Low);
                            inParams[data[0]] = data[1];
                        }
                    }

                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = classInstance.InvokeMethod(this.Method.Get(this.ActivityContext), inParams, null);
                    if (outParams != null)
                    {
                        this.ReturnValue.Set(this.ActivityContext, outParams["ReturnValue"].ToString());
                    }
                }
            }
            else
            {
                using (ManagementClass mgmtClass = new ManagementClass(this.Scope, new ManagementPath(managementPath), null))
                {
                    // Obtain in-parameters for the method
                    ManagementBaseObject inParams = mgmtClass.GetMethodParameters(this.Method.Get(this.ActivityContext));
                    this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Method: {0}", this.Method.Get(this.ActivityContext)), BuildMessageImportance.Low);

                    if (this.MethodParameters != null)
                    {
                        // Add the input parameters.
                        foreach (string[] data in this.MethodParameters.Get(this.ActivityContext).Select(param => param.Split(new[] { "#~#" }, StringSplitOptions.RemoveEmptyEntries)))
                        {
                            this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Param: {0}. Value: {1}", data[0], data[1]), BuildMessageImportance.Low);
                            inParams[data[0]] = data[1];
                        }
                    }

                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = mgmtClass.InvokeMethod(this.Method.Get(this.ActivityContext), inParams, null);
                    if (outParams != null)
                    {
                        this.ReturnValue.Set(this.ActivityContext, outParams["ReturnValue"].ToString());
                    }
                }
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Изменяет имя компьютера
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public bool ChangeComputerName(string name)
 {
     bool complete = false;
     try
     {
         ManagementObject objMO = new ManagementObject(string.Format("Win32_ComputerSystem.Name='{0}'",
         Environment.MachineName));
         ManagementBaseObject wGroup = objMO.GetMethodParameters("Rename");
         wGroup.SetPropertyValue("Name", name);
         ManagementBaseObject setwGroup = objMO.InvokeMethod("Rename", wGroup, null);
         complete = true;
     }
     catch (Exception) { throw; }
     return complete;
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Rename the computer in workgroup
        /// </summary>
        /// <param name="computerSystem"></param>
        /// <param name="computerName"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        private int RenameComputer(ManagementObject computerSystem, string computerName, string newName)
        {
            string domainUserName = null;
            string domainPassword = null;

            if (DomainName != null && Credential != null)
            {
                // The rename operation happens after the computer is joined to the new domain, so we should provide
                // the domain user name and password to the rename operation
                domainUserName = Credential.UserName;
                domainPassword = Utils.GetStringFromSecureString(Credential.Password);
            }

            ManagementBaseObject renameParameter = computerSystem.GetMethodParameters("Rename");
            renameParameter.SetPropertyValue("Name", newName);
            renameParameter.SetPropertyValue("UserName", domainUserName);
            renameParameter.SetPropertyValue("Password", domainPassword);

            ManagementBaseObject result = computerSystem.InvokeMethod("Rename", renameParameter, null);
            Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Rename method is invoked");
            int returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture);
            if (returnCode != 0)
            {
                var ex = new Win32Exception(returnCode);
                string errMsg;
                string errorId;
                if (WorkgroupName != null)
                {
                    errMsg = StringUtil.Format(ComputerResources.FailToRenameAfterJoinWorkgroup, computerName,
                                               WorkgroupName, newName, ex.Message);
                    errorId = "FailToRenameAfterJoinWorkgroup";
                }
                else
                {
                    errMsg = StringUtil.Format(ComputerResources.FailToRenameAfterJoinDomain, computerName, DomainName,
                                               newName, ex.Message);
                    errorId = "FailToRenameAfterJoinDomain";
                }

                WriteErrorHelper(errMsg, errorId, computerName, ErrorCategory.OperationStopped, false);
            }
            return returnCode;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Join in a new workgroup from the current workgroup
        /// </summary>
        /// <param name="computerSystem"></param>
        /// <param name="computerName"></param>
        /// <param name="oldDomainName"></param>
        /// <returns></returns>
        private int JoinWorkgroup(ManagementObject computerSystem, string computerName, string oldDomainName)
        {
            ManagementBaseObject joinWorkgroupParam = computerSystem.GetMethodParameters("JoinDomainOrWorkgroup");
            joinWorkgroupParam.SetPropertyValue("Name", WorkgroupName);
            joinWorkgroupParam.SetPropertyValue("UserName", null);
            joinWorkgroupParam.SetPropertyValue("Password", null);
            joinWorkgroupParam.SetPropertyValue("FJoinOptions", 0); // join a workgroup

            ManagementBaseObject result = computerSystem.InvokeMethod("JoinDomainOrWorkgroup", joinWorkgroupParam, null);
            Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Join method is invoked");
            int returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture);
            if (returnCode != 0)
            {
                var ex = new Win32Exception(returnCode);
                string errMsg;
                if (oldDomainName != null)
                {
                    errMsg =
                        StringUtil.Format(ComputerResources.FailToSwitchFromDomainToWorkgroup, computerName,
                                          oldDomainName, WorkgroupName, ex.Message);
                }
                else
                {
                    errMsg = StringUtil.Format(ComputerResources.FailToJoinWorkGroup, computerName, WorkgroupName,
                                               ex.Message);
                }

                WriteErrorHelper(errMsg, "FailToJoinWorkGroup", computerName, ErrorCategory.OperationStopped, false);
            }
            return returnCode;
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Join a domain from a workgroup
        /// </summary>
        /// <remarks>
        /// If a computer is already in a domain, we first unjoin it from its current domain, and
        /// then do the join operation to the new domain. So when this method is invoked, we are 
        /// currently in a workgroup
        /// </remarks>
        /// <param name="computerSystem"></param>
        /// <param name="computerName"></param>
        /// <param name="oldDomainName"></param>
        /// <param name="curWorkgroupName"></param>
        /// <returns></returns>
        private int JoinDomain(ManagementObject computerSystem, string computerName, string oldDomainName, string curWorkgroupName)
        {
            string joinDomainUserName = Credential != null ? Credential.UserName : null;
            string joinDomainPassword = Credential != null ? Utils.GetStringFromSecureString(Credential.Password) : null;

            ManagementBaseObject joinDomainParameter = computerSystem.GetMethodParameters("JoinDomainOrWorkgroup");
            joinDomainParameter.SetPropertyValue("Name", DomainName);
            joinDomainParameter.SetPropertyValue("UserName", joinDomainUserName);
            joinDomainParameter.SetPropertyValue("Password", joinDomainPassword);
            joinDomainParameter.SetPropertyValue("AccountOU", OUPath);
            joinDomainParameter.SetPropertyValue("FJoinOptions", _joinDomainflags);

            ManagementBaseObject result = computerSystem.InvokeMethod("JoinDomainOrWorkgroup", joinDomainParameter, null);
            Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Join method is invoked");
            int returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture);
            if (returnCode != 0)
            {
                var ex = new Win32Exception(returnCode);
                string errMsg;
                string errorId;
                if (oldDomainName != null)
                {
                    errMsg = StringUtil.Format(ComputerResources.FailToJoinNewDomainAfterUnjoinOldDomain,
                                                   computerName, oldDomainName, DomainName, ex.Message);
                    errorId = "FailToJoinNewDomainAfterUnjoinOldDomain";
                }
                else
                {
                    errMsg = StringUtil.Format(ComputerResources.FailToJoinDomainFromWorkgroup, computerName,
                                                   DomainName, curWorkgroupName, ex.Message);
                    errorId = "FailToJoinDomainFromWorkgroup";
                }

                WriteErrorHelper(errMsg, errorId, computerName, ErrorCategory.OperationStopped, false);
            }
            return returnCode;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Unjoin the computer from its current domain
        /// <remarks>
        /// In the DomainParameterSet, the UnjoinDomainCredential is our first choice to unjoin a domain.
        /// But if the UnjoinDomainCredential is not specified, the DomainCredential will be our second 
        /// choice. This is to keep the backward compatibility. In Win7, we can do:
        ///      Add-Computer -DomainName domain1 -Credential $credForDomain1AndDomain2
        /// to switch the local machine that is currently in domain2 to domain1.
        /// 
        /// Since DomainCredential has an alias "Credential", the same command should still work for the
        /// new Add-Computer cmdlet.
        /// 
        /// In the WorkgroupParameterSet, the UnjoinDomainCredential is the only choice.
        /// </remarks>
        /// </summary>
        /// <param name="computerSystem"></param>
        /// <param name="computerName"></param>
        /// <param name="curDomainName"></param>
        /// <param name="dUserName"></param>
        /// <param name="dPassword"></param>
        /// <returns></returns>
        private int UnjoinDomain(ManagementObject computerSystem, string computerName, string curDomainName, string dUserName, string dPassword)
        {
            ManagementBaseObject unjoinDomainParameter = computerSystem.GetMethodParameters("UnjoinDomainOrWorkgroup");
            unjoinDomainParameter.SetPropertyValue("UserName", dUserName);
            unjoinDomainParameter.SetPropertyValue("Password", dPassword);
            unjoinDomainParameter.SetPropertyValue("FUnjoinOptions", 4); // default option, disable the active directory

            ManagementBaseObject result = computerSystem.InvokeMethod("UnjoinDomainOrWorkgroup", unjoinDomainParameter, null);
            Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Unjoin method is invoked");
            int returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture);
            if (returnCode != 0)
            {
                var ex = new Win32Exception(returnCode);
                WriteErrorHelper(ComputerResources.FailToUnjoinDomain, "FailToUnjoinDomain", computerName,
                                 ErrorCategory.OperationStopped, false, computerName, curDomainName, ex.Message);
            }
            return returnCode;
        }
Ejemplo n.º 27
0
        private void CreateSite(ManagementScope scope)
        {
            var serverBinding = new ManagementClass(scope, new ManagementPath("ServerBinding"), null).CreateInstance();
            serverBinding["Port"] = "6060";

            var iis = new ManagementObject(scope, new ManagementPath("IIsWebService='W3SVC'"), null);
            ManagementBaseObject createNewSiteArgs = iis.GetMethodParameters("CreateNewSite");
            createNewSiteArgs["ServerComment"] = "My New Site";
            createNewSiteArgs["ServerBindings"] = new[] {serverBinding};
            createNewSiteArgs["PathOfRootVirtualDir"] = @"c:\somedirectory";

            var result = iis.InvokeMethod("CreateNewSite", createNewSiteArgs, null);
            Console.WriteLine(result["ReturnValue"]);
        }
Ejemplo n.º 28
0
 public static string Read(ManagementObject session, string path)
 {
     ManagementBaseObject inparam = session.GetMethodParameters("GetValue");
     inparam["Pathname"] = path;
     ManagementBaseObject outparam = session.InvokeMethod("GetValue", inparam, null);
     return (string)outparam["value"];
 }
Ejemplo n.º 29
0
            /// <summary>
            /// Изменяет имя рабочей группы, только если не является чатью домена
            /// </summary>
            /// <param name="workgroup"></param>
            /// <returns></returns>
            public bool SetWorkgroup(string workgroup)
            {
                bool complete = false;
                try
                {
                    ManagementObject objMO = new ManagementObject(string.Format("Win32_ComputerSystem.Name='{0}'",
                    Environment.MachineName));
                    if (!(bool)objMO.GetPropertyValue("PartOfDomain"))
                    {
                        ManagementBaseObject wGroup = objMO.GetMethodParameters("JoinDomainOrWorkgroup");
                        wGroup.SetPropertyValue("Name", workgroup);

                        ManagementBaseObject setwGroup = objMO.InvokeMethod("JoinDomainOrWorkgroup", wGroup, null);
                        complete = true;
                        return complete;
                    }

                }
                catch (Exception) { throw; }
                return complete;
            }
Ejemplo n.º 30
0
 public static void Write(ManagementObject session, string path, string value)
 {
     ManagementBaseObject inparam = session.GetMethodParameters("SetValue");
     inparam["Pathname"] = path;
     inparam["value"] = value;
     session.InvokeMethod("SetValue", inparam, null);
 }
        public static ReturnValue ChangeStartMode(string svcName, StartMode startMode)
        {
            string objPath = string.Format("Win32_Service.Name='{0}'", svcName);
            using (var service = new ManagementObject(new ManagementPath(objPath)))
            {
                ManagementBaseObject inParams = service.GetMethodParameters("ChangeStartMode");
                inParams["StartMode"] = startMode.ToString();
                try
                {
                    ManagementBaseObject outParams = service.InvokeMethod("ChangeStartMode", inParams, null);

                    return (ReturnValue) Enum.Parse(typeof (ReturnValue), outParams["ReturnValue"].ToString());
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }