/// <summary> /// Retrieve String value from registry path. /// </summary> /// <param name="wmiRegistry">Management Object</param> /// <param name="keyPath">Registry Path</param> /// <param name="keyName">Key Name</param> /// <param name="stringValue">Key Value</param> /// <returns></returns> private ResultCodes getRegistryStringValue( ManagementClass wmiRegistry, string keyPath, string keyName, out string stringValue) { ManagementBaseObject inputParameters = wmiRegistry.GetMethodParameters(RegistryMethodNames.GET_MULTI_STRING_VALUE); inputParameters.SetPropertyValue(RegistryPropertyNames.DEF_KEY, RegistryTrees.HKEY_LOCAL_MACHINE); inputParameters.SetPropertyValue(RegistryPropertyNames.SUB_KEY_NAME, keyPath); inputParameters.SetPropertyValue(RegistryPropertyNames.VALUE_NAME, keyName); ManagementBaseObject outputParameters = null; stringValue = null; ResultCodes resultCode = Lib.InvokeRegistryMethod(m_taskId, wmiRegistry, RegistryMethodNames.GET_STRING_VALUE, keyPath, inputParameters, out outputParameters); if (resultCode == ResultCodes.RC_SUCCESS && null != outputParameters) { using (outputParameters) { stringValue = outputParameters.GetPropertyValue(RegistryPropertyNames.S_VALUE) as string; } } return(resultCode); }
/// <summary> /// Permet d'ajout une valeur dans le chemin donnée en paramètre. /// </summary> /// <param name="subKey">Chemin ou mettre la valeur.</param> /// <param name="valueName">Nom de la valeur : exemple MANIFEST</param> /// <param name="value">Valeur à mettre. Ex : le chemin de Nemo.</param> /// <returns></returns> public Task AddValueInUserAsync(string hostName, string subKey, string valueName, string value) { return Task.Factory.StartNew(() => { try { ManagementScope scope = new ManagementScope("\\\\" + hostName + "\\root\\CIMV2", _connectionOption); scope.Connect(); ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters("SetStringValue"); inParams.SetPropertyValue("hDefKey", 0x80000003); inParams.SetPropertyValue("sSubKeyName", subKey); inParams.SetPropertyValue("sValueName", valueName); inParams.SetPropertyValue("sValue", value); registry.InvokeMethod("SetStringValue", inParams, null); _logger.Success("Ajout/Mis à jour de la valeur " + valueName); } catch (Exception) { _logger.Error("Erreur sur l'ajout ou mise à jour de la valeur " + valueName); } }); }
/// <summary> /// Set's WINS of the local machine /// </summary> /// <param name="NIC">NIC Address</param> /// <param name="priWINS">Primary WINS server address</param> /// <param name="secWINS">Secondary WINS server address</param> /// <remarks>Requires a reference to the System.Management namespace</remarks> public void setWINS(string NIC, string priWINS, string secWINS) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { if (objMO["Caption"].Equals(NIC)) { try { ManagementBaseObject setWINS; ManagementBaseObject wins = objMO.GetMethodParameters("SetWINSServer"); wins.SetPropertyValue("WINSPrimaryServer", priWINS); wins.SetPropertyValue("WINSSecondaryServer", secWINS); setWINS = objMO.InvokeMethod("SetWINSServer", wins, null); } catch (Exception) { throw; } } } } }
/// <summary> /// Get List of running virtual machine config files. /// Each config file represent a running instance of virtual machine in memory. /// </summary> /// <param name="strKeyPath">Registry Path</param> /// <returns>List of Virtual Machines</returns> private string getRunningVMs(string strRegKeyPath) { StringBuilder builder = new StringBuilder(); ManagementBaseObject moInput = m_wmiRegistry.GetMethodParameters(RegistryMethodNames.ENUM_KEY); moInput.SetPropertyValue(RegistryPropertyNames.DEF_KEY, RegistryTrees.HKEY_USERS); moInput.SetPropertyValue(RegistryPropertyNames.SUB_KEY_NAME, strRegKeyPath); ManagementBaseObject moOutput = m_wmiRegistry.InvokeMethod(RegistryMethodNames.ENUM_VALUES, moInput, null); if (moOutput != null) { string[] strValues = moOutput.GetPropertyValue(RegistryPropertyNames.NAMES) as string[]; if (strValues != null && strValues.Length > 0) { foreach (string strValue in strValues) { if (builder.Length > 0) { builder.Append(BdnaDelimiters.DELIMITER_TAG); } builder.Append(strValue); } } } return(builder.ToString()); }
/// <summary> /// Set's WINS of the local machine /// </summary> /// <param name="NIC">NIC Address</param> /// <param name="priWINS">Primary WINS server address</param> /// <param name="secWINS">Secondary WINS server address</param> /// <remarks>Requires a reference to the System.Management namespace</remarks> private static void SetWINS(string priWINS, string secWINS, string macAddress) { using (ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration")) { ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { if (objMO["MACAddress"].ToString().ToUpperInvariant().Equals(macAddress.ToUpperInvariant())) { try { ManagementBaseObject wins = objMO.GetMethodParameters("SetWINSServer"); wins.SetPropertyValue("WINSPrimaryServer", priWINS); wins.SetPropertyValue("WINSSecondaryServer", secWINS); objMO.InvokeMethod("SetWINSServer", wins, null); } catch (Exception) { throw; } } } } } }
//http://www.windows-tech.info/13/73e33d211c023671.php static void createShadow(string Volume) { try { ManagementClass shadowCopy = new ManagementClass("Win32_ShadowCopy"); ManagementBaseObject inParams = shadowCopy.GetMethodParameters("Create"); //int numItems = inParams.Properties.Count; //Console.WriteLine("[*] Number of items: " + numItems); inParams.SetPropertyValue("Volume", Volume); inParams.SetPropertyValue("Context", "ClientAccessible"); ManagementBaseObject outParams = shadowCopy.InvokeMethod("Create", inParams, null); if (outParams["ReturnValue"].ToString() == "0") { Console.WriteLine("[*] Attempting to create a shadow copy. ShadowID: " + outParams["ShadowID"].ToString()); } } catch (ManagementException err) { Console.WriteLine("An error occurred while trying to execute the WMI method: " + err.Message); Console.WriteLine(err.StackTrace); } }
public NetworkAdapterVM(ManagementBaseObject adapter) { this.Adapter = adapter; Description = (string)adapter[nameof(Description)]; DNSDomain = (string)adapter[nameof(DNSDomain)]; DomainDNSRegistrationEnabled = (bool)adapter[nameof(DomainDNSRegistrationEnabled)]; DNSHostName = (string)adapter[nameof(DNSHostName)]; DefaultIPGateway = (string)adapter[nameof(DefaultIPGateway)]; DHCPEnabled = (bool)adapter[nameof(DHCPEnabled)]; DHCPServer = (string)adapter[nameof(DHCPServer)]; MACAddress = (string)adapter[nameof(MACAddress)]; WINSPrimaryServer = (string)adapter[nameof(WINSPrimaryServer)]; var ip = (string[])adapter[nameof(IPAddress)]; if (ip != null) { IPAddress = new List <string>(ip); } else { IPAddress = new List <string>(); } var subnet = (string[])adapter[nameof(IPAddress)]; if (subnet != null) { IPAddress = new List <string>(subnet); } else { IPAddress = new List <string>(); } var dnsServers = (string[])adapter[nameof(DNSServerSearchOrder)]; if (subnet != null) { DNSServerSearchOrder = new List <string>(dnsServers); } else { DNSServerSearchOrder = new List <string>(); } UpdateConfiguration = new RelayCommand(new Action(() => { Adapter.SetPropertyValue(nameof(Description), Description); Adapter.SetPropertyValue(nameof(DNSDomain), DNSDomain); Adapter.SetPropertyValue(nameof(IPAddress), IPAddress); })); }
/// <summary> /// Validates the value entered when a cell is editted. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (!this.dataGridView1.CurrentCell.IsInEditMode || this.selectedObject == null || this.selectedProperty == null) { return; } string guid = this.dataGridView1.CurrentNode.Tag.ToString(); // Ignore unchanged values if (!this.SelectedProperty.GetValueAsString().Equals(e.FormattedValue.ToString())) { // Update object try { TreeGridNode parent = this.dataGridView1.CurrentNode.Parent; ManagementBaseObject target = this.objectMap[guid]; string property = this.propertyMap[guid].Name; object value = e.FormattedValue; // Apply new value target.SetPropertyValue(property, value); // Move up a level while (parent != null && this.objectMap.ContainsKey(parent.Tag.ToString())) { value = target; target = this.objectMap[parent.Tag.ToString()]; if (this.propertyMap.ContainsKey(parent.Tag.ToString())) { property = this.propertyMap[parent.Tag.ToString()].Name; target.SetPropertyValue(property, value); } parent = parent.Parent; } this.OnValidationSucceeded(); } catch (Exception x) { SystemSounds.Exclamation.Play(); e.Cancel = true; this.dataGridView1.Rows[e.RowIndex].ErrorText = x.Message; this.OnValidationFailed(x); } } }
private void FillWmiObjectUNCFromFtpAccount(ManagementBaseObject obj, FtpAccount account) { if (account.Folder.StartsWith(@"\\") && !String.IsNullOrEmpty(account.Name) && !String.IsNullOrEmpty(account.Password)) { // obj.SetPropertyValue("UNCUserName", GetQualifiedAccountName(account.Name)); obj.SetPropertyValue("UNCPassword", account.Password); } }
public UInt32 RunCommand(string command) { try { this.ManagementScope.Connect(); } catch (Exception ex) { throw new Exception("Management connect to remote machine {0} as user {1} failed with the following error {2}".FormatWith(this.machine, this.userName, ex.Message), ex); } ObjectGetOptions objectGetOptions = new ObjectGetOptions(); ManagementPath managementPath = new ManagementPath("Win32_Process"); this.ExitCode = 0; this.ProcessExited = false; Log.Info("Starting command: {0} on remote machine {1} as {2}\\{3}...", command, this.machine, this.Domain, this.userName); using (ManagementClass managementClass = new ManagementClass(this.ManagementScope, managementPath, objectGetOptions)) { using (ManagementBaseObject input = managementClass.GetMethodParameters("Create")) { input.SetPropertyValue("CommandLine", command); input.SetPropertyValue("CurrentDirectory", this.WorkingDirectory); Log.Info("Used working directory: {0}".FormatWith(input.GetPropertyValue("CurrentDirectory").ToString())); using (ManagementBaseObject output = managementClass.InvokeMethod("Create", input, null)) { try { if ((uint)output["returnValue"] != 0) { throw new Exception("Error while starting process " + command + ".\r\nCreation returned an exit code of " + output["returnValue"] + ". It was launched as " + this.userName + " on " + this.machine); } else { this.processId = Convert.ToUInt32(output.GetPropertyValue("ProcessID").ToString()); Log.Info("Started command: {0} on remote machine {1}\r\nProcessId: {2}", command, this.machine, this.processId); } } catch (Exception ex) { Log.Error("Failed to start process with command '{0}' on machine {1}.".FormatWith(command, this.machine)); ExceptionHelper.CentralProcess(ex); } } } } return(this.processId); }
/// <summary> /// Install a Windows Installer Package /// </summary> /// <param name="sPath"></param> /// <param name="sOptions"></param> /// <returns>MSI Exit Code</returns> public UInt32 InstallMSI(string sPath, string sOptions) { WMIProvider oProv = new WMIProvider(oWMIProvider.mScope.Clone()); oProv.mScope.Path.NamespacePath = @"root\cimv2"; ManagementClass MC = oProv.GetClass("Win32_Product"); ManagementBaseObject inParams = MC.GetMethodParameters("Install"); inParams.SetPropertyValue("PackageLocation", sPath); inParams.SetPropertyValue("Options", sOptions); ManagementBaseObject Result = MC.InvokeMethod("Install", inParams, null); return((UInt32)Result.GetPropertyValue("ReturnValue")); }
public bool AddPrinter(string sPrinterName, CancellationToken token) { if (token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } try { objManagementScope = new ManagementScope(ManagementPath.DefaultPath); objManagementScope.Connect(); ManagementClass objPrinterClass = new ManagementClass(new ManagementPath("Win32_Printer"), null); ManagementBaseObject objInputParameters = objPrinterClass.GetMethodParameters("AddPrinterConnection"); objInputParameters.SetPropertyValue("Name", sPrinterName); if (IsPrinterInstalled(sPrinterName, token)) { DisconnectPrinter(sPrinterName, token); } objPrinterClass?.InvokeMethod("AddPrinterConnection", objInputParameters, null); OnAtomicStateChange?.Invoke(this, new StringEventArgs($"Completed adding printer : {sPrinterName}")); return(true); } catch (OperationCanceledException) { throw; } catch (Exception) { OnAtomicStateError?.Invoke(this, new StringEventArgs($"Failed adding printer : {sPrinterName}")); return(false); } }
/// <summary> /// Permet de retourner la liste des keys dans un chemin donnée. /// </summary> /// <param name="subKey"></param> /// <returns></returns> public Task<string[]> GetKeysInUserAsync(string hostName, string subKey) { return Task.Factory.StartNew(() => { ManagementScope scope = new ManagementScope("\\\\" + hostName + "\\root\\CIMV2", _connectionOption); scope.Connect(); ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters("EnumKey"); inParams.SetPropertyValue("hDefKey", 0x80000003); inParams.SetPropertyValue("sSubKeyName", subKey); return (string[])registry.InvokeMethod("EnumKey", inParams, null).Properties["sNames"].Value; }); }
public static void SetPropertyValue(ManagementBaseObject wmiClass, string propertyName, object value) { const string method = "SetPropertyValue"; if (wmiClass == null) { throw new NullParameterException(typeof(WmiUtil), method, "wmiClass"); } if (propertyName == null) { throw new NullParameterException(typeof(WmiUtil), method, "propertyName"); } try { wmiClass.SetPropertyValue(propertyName, value); } catch (ManagementException ex) { string classText = null; try { classText = wmiClass.GetText(TextFormat.Mof); } catch (System.Exception) { } throw new WmiPropertySetException(typeof(WmiUtil), method, propertyName, wmiClass.ClassPath.ToString(), classText, value, ex); } }
private int RenameComputer(ManagementObject computerSystem, string computerName, string newName) { string str; string str1; string userName = null; string stringFromSecureString = null; if (this._domainName != null && this.Credential != null) { userName = this.Credential.UserName; stringFromSecureString = Utils.GetStringFromSecureString(this.Credential.Password); } ManagementBaseObject methodParameters = computerSystem.GetMethodParameters("Rename"); methodParameters.SetPropertyValue("Name", newName); methodParameters.SetPropertyValue("UserName", userName); methodParameters.SetPropertyValue("Password", stringFromSecureString); ManagementBaseObject managementBaseObject = computerSystem.InvokeMethod("Rename", methodParameters, null); int num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture); if (num != 0) { Win32Exception win32Exception = new Win32Exception(num); if (this._workgroupName == null) { object[] message = new object[4]; message[0] = computerName; message[1] = this._domainName; message[2] = newName; message[3] = win32Exception.Message; str = StringUtil.Format(ComputerResources.FailToRenameAfterJoinDomain, message); str1 = "FailToRenameAfterJoinDomain"; } else { object[] objArray = new object[4]; objArray[0] = computerName; objArray[1] = this._workgroupName; objArray[2] = newName; objArray[3] = win32Exception.Message; str = StringUtil.Format(ComputerResources.FailToRenameAfterJoinWorkgroup, objArray); str1 = "FailToRenameAfterJoinWorkgroup"; } this.WriteErrorHelper(str, str1, computerName, ErrorCategory.OperationStopped, false, new object[0]); } return(num); }
public void SetWINS(string primaryWINS, string secondaryWINS) { if (!Enabled) { return; } try { ManagementBaseObject setWINS; ManagementBaseObject wins = moConfig.GetMethodParameters("SetWINSServer"); wins.SetPropertyValue("WINSPrimaryServer", primaryWINS); wins.SetPropertyValue("WINSSecondaryServer", secondaryWINS); setWINS = moConfig.InvokeMethod("SetWINSServer", wins, null); } catch (Exception) { throw; } }
public int JoinADRemotePC(String Name, String domain, NetworkCredential localaccount, NetworkCredential domainaccount, String OU) { int JOIN_DOMAIN = 1; int ACCT_CREATE = 2; var remoteControlObject = new ManagementPath { ClassName = "Win32_ComputerSystem", Server = Name, Path = Name + "\\root\\cimv2:Win32_ComputerSystem", NamespacePath = "\\\\" + Name + "\\root\\cimv2:Win32_ComputerSystem" }; var conn = new ConnectionOptions { Authentication = AuthenticationLevel.PacketPrivacy, // Impersonation = ImpersonationLevel.Impersonate, //EnablePrivileges = true, Username = Name + "\\" + localaccount.UserName, Password = localaccount.Password }; var remoteScope = new ManagementScope(remoteControlObject, conn); remoteScope.Connect(); var remoteSystem = new ManagementObject(remoteScope, remoteControlObject, null); ManagementBaseObject newRemoteSystemName = remoteSystem.GetMethodParameters("JoinDomainorWorkgroup"); var methodOptions = new InvokeMethodOptions(); newRemoteSystemName.SetPropertyValue("Name", domain); newRemoteSystemName.SetPropertyValue("UserName", domainaccount.UserName); newRemoteSystemName.SetPropertyValue("Password", domainaccount.Password); newRemoteSystemName.SetPropertyValue("AccountOU", OU); newRemoteSystemName.SetPropertyValue("FJoinOptions", JOIN_DOMAIN + ACCT_CREATE); methodOptions.Timeout = new TimeSpan(0, 10, 0); ManagementBaseObject outParams = remoteSystem.InvokeMethod("JoinDomainorWorkgroup", newRemoteSystemName, null); return((int)outParams.Properties["ReturnValue"].Value); }
/// <summary> /// Get one registry string value /// </summary> /// <param name="strKeyPath">Key Path</param> /// <param name="strKeyName">Key Name</param> /// <returns>Value</returns> private ResultCodes GetRegistryStringValue (ManagementClass wmiRegistry, string strKeyPath, string strKeyName, out string strKeyValue) { ResultCodes resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REGISTRY; strKeyValue = String.Empty; using (ManagementBaseObject inputParameters = wmiRegistry.GetMethodParameters(RegistryMethodNames.GET_STRING_VALUE)) { inputParameters.SetPropertyValue(RegistryPropertyNames.SUB_KEY_NAME, strKeyPath); inputParameters.SetPropertyValue(RegistryPropertyNames.VALUE_NAME, strKeyName); ManagementBaseObject outputParameters = null; resultCode = Lib.InvokeRegistryMethod(m_taskId, wmiRegistry, RegistryMethodNames.GET_STRING_VALUE, strKeyPath, inputParameters, out outputParameters); if (resultCode == ResultCodes.RC_SUCCESS && null != outputParameters) { using (outputParameters) { strKeyValue = outputParameters.GetPropertyValue(RegistryPropertyNames.S_VALUE) as string; } } } return(resultCode); }
private int UnjoinDomain(ManagementObject computerSystem, string computerName, string curDomainName, string dUserName, string dPassword) { ManagementBaseObject methodParameters = computerSystem.GetMethodParameters("UnjoinDomainOrWorkgroup"); methodParameters.SetPropertyValue("UserName", dUserName); methodParameters.SetPropertyValue("Password", dPassword); methodParameters.SetPropertyValue("FUnjoinOptions", 4); ManagementBaseObject managementBaseObject = computerSystem.InvokeMethod("UnjoinDomainOrWorkgroup", methodParameters, null); int num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture); if (num != 0) { Win32Exception win32Exception = new Win32Exception(num); object[] message = new object[3]; message[0] = computerName; message[1] = curDomainName; message[2] = win32Exception.Message; this.WriteErrorHelper(ComputerResources.FailToUnjoinDomain, "FailToUnjoinDomain", computerName, ErrorCategory.OperationStopped, false, message); } return(num); }
/// <summary> /// Get all Immediate subKey of one registry branch (non-recursive) /// </summary> /// <param name="strKeyPath">Path</param> /// <returns>Array of SubKeys</returns> private ResultCodes GetImmediateRegistrySubKeys(ManagementClass wmiRegistry, string strKeyPath, out string[] strSubKeys) { ResultCodes resultCode = ResultCodes.RC_INSUFFICIENT_PRIVILEGE_TO_READ_REGISTRY; strSubKeys = null; using (ManagementBaseObject inputParameters = wmiRegistry.GetMethodParameters(RegistryMethodNames.ENUM_KEY)) { inputParameters.SetPropertyValue(RegistryPropertyNames.DEF_KEY, RegistryTrees.HKEY_LOCAL_MACHINE); inputParameters.SetPropertyValue(RegistryPropertyNames.SUB_KEY_NAME, strKeyPath); ManagementBaseObject outputParameters = null; resultCode = Lib.InvokeRegistryMethod(m_taskId, wmiRegistry, RegistryMethodNames.ENUM_KEY, strKeyPath, inputParameters, out outputParameters); if (ResultCodes.RC_SUCCESS == resultCode && null != outputParameters) { using (outputParameters) { strSubKeys = outputParameters.GetPropertyValue(RegistryPropertyNames.NAMES) as string[]; } } } return(resultCode); }
/// <summary> /// Set's WINS of the local machine /// </summary> /// <param name="NIC">NIC Address</param> /// <param name="priWINS">Primary WINS server address</param> /// <param name="secWINS">Secondary WINS server address</param> /// <remarks>Requires a reference to the System.Management namespace</remarks> public void setWINS(string network, string priWINS, string secWINS) { // ----- Get network collection ----- var adapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration"); var networkCollection = adapterConfig.GetInstances(); foreach (ManagementObject adapter in networkCollection) { // ----- Find network adapter ----- string description = adapter["Description"] as string; if (string.Compare(description, network, StringComparison.InvariantCultureIgnoreCase) == 0) { // ----- Setting a WINS ----- ManagementBaseObject setWINS; ManagementBaseObject wins = adapter.GetMethodParameters("SetWINSServer"); wins.SetPropertyValue("WINSPrimaryServer", priWINS); wins.SetPropertyValue("WINSSecondaryServer", secWINS); setWINS = adapter.InvokeMethod("SetWINSServer", wins, null); } } }
static void MapPrinter(string sShare) { using (ManagementClass win32Printer = new ManagementClass("Win32_Printer")) { using (ManagementBaseObject inputParam = win32Printer.GetMethodParameters("AddPrinterConnection")) { // Replace <server_name> and <printer_name> with the actual server and // printer names. inputParam.SetPropertyValue("Name", sShare);//"\\\\<server_name>\\<printer_name>" using (ManagementBaseObject result = (ManagementBaseObject)win32Printer.InvokeMethod("AddPrinterConnection", inputParam, null)) { uint errorCode = (uint)result.Properties["returnValue"].Value; switch (errorCode) { case 0: Console.Out.WriteLine("[MapPrinter] Successfully connected printer."); break; case 5: Console.Out.WriteLine("[MapPrinter] Access Denied."); break; case 123: Console.Out.WriteLine("[MapPrinter] The filename, directory name, or volume label syntax is incorrect."); break; case 1801: Console.Out.WriteLine("[MapPrinter] Invalid Printer Name."); break; case 1930: Console.Out.WriteLine("[MapPrinter] Incompatible Printer Driver."); break; case 3019: Console.Out.WriteLine("[MapPrinter] The specified printer driver was not found on the system and needs to be downloaded."); break; default: Console.Out.WriteLine("[MapPrinter] Error mapping printer " + sShare + " errorCode=" + errorCode); break; } } } } }
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(); }
public int RenameRemotePC(String oldName, String newName, String domain, NetworkCredential localaccount, NetworkCredential domainaccount) { var remoteControlObject = new ManagementPath { ClassName = "Win32_ComputerSystem", Server = oldName, Path = oldName + "\\root\\cimv2:Win32_ComputerSystem.Name='" + oldName + "'", NamespacePath = "\\\\" + oldName + "\\root\\cimv2" }; var conn = new ConnectionOptions { Authentication = AuthenticationLevel.PacketPrivacy, Impersonation = ImpersonationLevel.Impersonate, EnablePrivileges = true, Username = oldName + "\\" + localaccount.UserName, Password = localaccount.Password }; var remoteScope = new ManagementScope(remoteControlObject, conn); remoteScope.Connect(); var remoteSystem = new ManagementObject(remoteScope, remoteControlObject, null); ManagementBaseObject newRemoteSystemName = remoteSystem.GetMethodParameters("Rename"); var methodOptions = new InvokeMethodOptions(); newRemoteSystemName.SetPropertyValue("Name", newName); newRemoteSystemName.SetPropertyValue("UserName", domainaccount.UserName); newRemoteSystemName.SetPropertyValue("Password", domainaccount.Password); methodOptions.Timeout = new TimeSpan(0, 10, 0); ManagementBaseObject outParams = remoteSystem.InvokeMethod("Rename", newRemoteSystemName, null); return((int)outParams.Properties["ReturnValue"].Value); }
/// <summary> /// Set's WINS of the local machine /// </summary> /// <param name="NIC">NIC Address</param> /// <param name="priWINS">Primary WINS server address</param> /// <param name="secWINS">Secondary WINS server address</param> /// <remarks>Requires a reference to the System.Management namespace</remarks> public static void setWINS(string NIC, string priWINS, string secWINS) { var objMOC = getOC(); foreach (ManagementObject objMO in objMOC) { if (objMO["MACAddress"].Equals(NIC)) { try { ManagementBaseObject setWINS; ManagementBaseObject wins = objMO.GetMethodParameters("SetWINSServer"); wins.SetPropertyValue("WINSPrimaryServer", priWINS); wins.SetPropertyValue("WINSSecondaryServer", secWINS); setWINS = objMO.InvokeMethod("SetWINSServer", wins, null); } catch (Exception) { throw; } } } }
private int JoinWorkgroup(ManagementObject computerSystem, string computerName, string oldDomainName) { string str; ManagementBaseObject methodParameters = computerSystem.GetMethodParameters("JoinDomainOrWorkgroup"); methodParameters.SetPropertyValue("Name", this._workgroupName); methodParameters.SetPropertyValue("UserName", null); methodParameters.SetPropertyValue("Password", null); methodParameters.SetPropertyValue("FJoinOptions", 0); ManagementBaseObject managementBaseObject = computerSystem.InvokeMethod("JoinDomainOrWorkgroup", methodParameters, null); int num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture); if (num != 0) { Win32Exception win32Exception = new Win32Exception(num); if (oldDomainName == null) { object[] message = new object[3]; message[0] = computerName; message[1] = this._workgroupName; message[2] = win32Exception.Message; str = StringUtil.Format(ComputerResources.FailToJoinWorkGroup, message); } else { object[] objArray = new object[4]; objArray[0] = computerName; objArray[1] = oldDomainName; objArray[2] = this._workgroupName; objArray[3] = win32Exception.Message; str = StringUtil.Format(ComputerResources.FailToSwitchFromDomainToWorkgroup, objArray); } this.WriteErrorHelper(str, "FailToJoinWorkGroup", computerName, ErrorCategory.OperationStopped, false, new object[0]); } return(num); }
/// <summary> /// Reinstall/Repair a Windows Installer Package based on the Packagename /// </summary> /// <param name="Name"></param> /// <param name="ReinstallMode"></param> /// <returns>MSI Exit Code or 99 if the PRoduct was not found</returns> public UInt32 ReinstallMSI_Name(string Name, reinstallMode ReinstallMode) { ManagementObjectCollection CliAgents; WMIProvider oProv = new WMIProvider(oWMIProvider.mScope.Clone()); oProv.mScope.Path.NamespacePath = @"root\cimv2"; CliAgents = oProv.ExecuteQuery("SELECT * FROM Win32_Product WHERE Name ='" + Name + "'"); foreach (ManagementObject CliAgent in CliAgents) { ManagementBaseObject inParams = CliAgent.GetMethodParameters("Reinstall"); inParams.SetPropertyValue("ReinstallMode", (UInt32)ReinstallMode); ManagementBaseObject result = CliAgent.InvokeMethod("Reinstalll", inParams, null); return(UInt32.Parse(result.GetPropertyValue("ReturnValue").ToString())); } return(99); }
private ManagementBaseObject InvokeMethod(string method, params KeyValuePair <string, object>[] parameters) { ManagementBaseObject param = bitlockerObject.GetMethodParameters(method); if (parameters != null) { foreach (var keyValue in parameters) { param.SetPropertyValue(keyValue.Key, keyValue.Value); } } ManagementBaseObject result = bitlockerObject.InvokeMethod(method, param, null); ErrorValidation(result); return(result); }
public static bool yazici_ekle(string sPrinterName) { try { oManagementScope = new ManagementScope(ManagementPath.DefaultPath); oManagementScope.Connect(); ManagementClass oPrinterClass = new ManagementClass(new ManagementPath("Win32_Printer"), null); ManagementBaseObject oInputParameters = oPrinterClass.GetMethodParameters("AddPrinterConnection"); oInputParameters.SetPropertyValue("Name", sPrinterName); oPrinterClass.InvokeMethod("AddPrinterConnection", oInputParameters, null); MessageBox.Show("başarılı"); return(true); } catch (Exception ex) { return(false); } }
private void mapPrinter(string BRD, string Nprinter) // Metodo para mapear impressoras rodando um arquvio .bat na instancia do usuario. Usando WMI { string sPrinterName = @"\\csbrprtsrv.la.hedani.net\P_SP00" + Nprinter; var connectoptions = new ConnectionOptions(); connectoptions.Impersonation = ImpersonationLevel.Default; connectoptions.EnablePrivileges = true; ManagementScope scope = new ManagementScope(@"\\" + BRD + @"\root\cimv2", connectoptions); scope.Connect(); ManagementClass oPrinterClass = new ManagementClass(new ManagementPath("Win32_Printer"), null); ManagementBaseObject oInputParameters = oPrinterClass.GetMethodParameters("AddPrinterConnection"); oInputParameters.SetPropertyValue("Name", sPrinterName); oPrinterClass.InvokeMethod("AddPrinterConnection", oInputParameters, null); }