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); } }
public static bool CreateRestorePoint(string description) { try { var restorePointName = "Optimisation Windows - " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString(); var managementPath = new ManagementPath(@"\\.\ROOT\DEFAULT:SystemRestore"); var systemRestoreClass = new ManagementClass(managementPath); var methodParameters = systemRestoreClass.Methods["CreateRestorePoint"].InParameters; methodParameters.Properties["Description"].Value = "Optimisation Windows - " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString(); methodParameters.Properties["EventType"].Value = 100u; methodParameters.Properties["Description"].Value = "Optimisation Windows - " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString(); var outParameters = systemRestoreClass.InvokeMethod("CreateRestorePoint", methodParameters, null); var hresult = unchecked ((int)(uint)outParameters["ReturnValue"]); return(true); } catch { return(false); } }
static void Main(string[] args) { try// Get the client's SMS_ClientSDK class. { ManagementScope s = new ManagementScope("root\\ccm\\clientsdk"); ManagementPath p = new ManagementPath("CCM_SoftwareCatalogUtilities"); ManagementClass cls = new ManagementClass(s, p, null); // get the catalog URL. ManagementBaseObject outSiteParams = cls.InvokeMethod("GetPortalUrlValue", null, null); Process pr = new Process(); pr.StartInfo.FileName = "c:\\Program Files\\Internet Explorer\\iexplore.exe"; pr.StartInfo.Arguments = (outSiteParams["PortalUrl"].ToString()); pr.Start(); } catch (ManagementException e) { Console.WriteLine("Failed to execute method", e); MessageBox.Show("Error! Could not find SCCM Store URL!", "Error"); } }
protected static void CreateRestorePoint() { try { LogMessage("CreateRestorePoint", "Creating Restore Point"); 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"] = "ASCOM Platform 6"; oInParams["RestorePointType"] = 0; oInParams["EventType"] = 100; ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null); LogMessage("CreateRestorePoint", "Returned from CreateRestorePoint method"); } catch (Exception ex) { LogError("CreateRestorePoint", ex.ToString()); } }
private void ConfigCleanup_Click(object sender, RoutedEventArgs e) { if (SelectedComputerList.SelectedIndex < 0) { System.Windows.MessageBox.Show("Please Select a Computer"); return; } System.Collections.IList // This grabs the selected computer variable ComputerSelected = SelectedComputerList.SelectedItems; // Run command on whatever computers we selected - probably need a beter way to do this at some point, with multiple threads etc foreach (object SelectedComputer in ComputerSelected) { ManagementClass processClass = new ManagementClass($@"\\{SelectedComputer}\root\cimv2:Win32_Process"); ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); // Command that executed on the remote host, can tinker with this to add the -force flag as well inParams["CommandLine"] = "cmd.exe /c del *.xml"; inParams["CurrentDirectory"] = @"C:\SysmonFiles"; ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null); Log.Information("All *.XML Files Removed From " + SelectedComputer); } }
public static void VMI_Invorke1() { // Get the object on which the // method will be invoked ManagementClass processClass = new ManagementClass("Win32_Process"); MethodDataCollection methods = processClass.Methods; foreach (MethodData item in methods) { Console.WriteLine(item.Name + " " + item.InParameters + " " + item.OutParameters); } // Create an array containing all // arguments for the method object[] methodArgs = { "notepad.exe", null, null, 0 }; //Execute the method object result = processClass.InvokeMethod("Create", methodArgs); //Display results Console.WriteLine("Creation of process returned: " + result); Console.WriteLine("Process id: " + methodArgs[3]); }
internal int ShareCreate(string ShareName, string FolderPath, string Description) { ManagementClass mgmtClass = new ManagementClass("Win32_Share"); ManagementBaseObject inParams = mgmtClass.GetMethodParameters("Create"); ManagementBaseObject outParams; inParams["Description"] = Description; inParams["Name"] = ShareName; inParams["Path"] = FolderPath; inParams["Type"] = 0x0; //disk drive inParams["Access"] = SecurityDescriptor(); //for Everyone full perms outParams = mgmtClass.InvokeMethod("Create", inParams, null); if ((uint)(outParams.Properties["ReturnValue"].Value) != 0) { string errCode = Enum.GetName(typeof(shareCreateErrorCodes), outParams.Properties["ReturnValue"].Value); MessageBox.Show(String.Format("Unable to create a network share. The error message was {0}\n\nShareName = {1}\nFolderPath = {2}", errCode, ShareName, FolderPath)); return(1); } else { return(0); } }
/// <summary> /// /// </summary> /// <param name="zoneName"></param> /// <param name="host"></param> /// <param name="mailServer"></param> /// <param name="mailServerPriority"></param> /// <remarks>Supports managed resources disposal</remarks> private void AddMXRecord(string zoneName, string host, string mailServer, int mailServerPriority) { // add record using (ManagementClass clsRR = wmi.GetClass("MicrosoftDNS_MXType")) { clsRR.InvokeMethod("CreateInstanceFromPropertyData", new object[] { GetDnsServerName(), zoneName, CorrectHostName(zoneName, host), 1, MinimumTTL, mailServerPriority, mailServer }); } // update SOA record if (bulkRecords) { return; } UpdateSoaRecord(zoneName); }
private void testFunction() { ConnectionOptions oConn = new ConnectionOptions(); string hostname = ""; System.Management.ManagementScope scope = new System.Management.ManagementScope(@"\\" + hostname + @"\root\cimv2", oConn); scope.Connect(); ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters("GetStringValue"); inParams["hDefKey"] = 0x80000002; // HKEY_LOCAL_MACHINE; inParams["sSubKeyName"] = "SOFTWARE\\Microsoft\\.NETFramework"; inParams["sValueName"] = "InstallRoot"; ManagementBaseObject outParams = registry.InvokeMethod("GetStringValue", inParams, null); if (outParams.Properties["sValue"].Value != null) { // output = outParams.Properties["sValue"].Value.ToString(); } }
public static void RunProcessOnRemoteMachine(string remoteMachine, string strPathToTheExe, string usernameAndDomain, string password) { try { var connection = new ConnectionOptions(); connection.Impersonation = ImpersonationLevel.Impersonate; connection.Authentication = AuthenticationLevel.Packet; connection.EnablePrivileges = true; connection.Username = usernameAndDomain; connection.Password = password; var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", remoteMachine), connection); wmiScope.Connect(); var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); var inParams = wmiProcess.GetMethodParameters("Create"); inParams["CommandLine"] = strPathToTheExe; var outParams = wmiProcess.InvokeMethod("Create", inParams, null); Console.WriteLine("Process ID: " + outParams["processId"]); } catch (Exception ex) { Console.WriteLine("Error occurred : " + ex.Message.ToString()); } }
public void RunMSIRemote() { if (Scope == null) { BuildConnection(); } if (!Scope.IsConnected) { BuildConnection(); } try { if (Scope.IsConnected) { DataManager.CurrentStatus = DataManager.InstallStatus.RunningMSI; ManagementPath Path = new ManagementPath("Win32_Product"); using (ManagementClass Class = new ManagementClass(Scope, Path, null)) { using (ManagementBaseObject inParam = Class.GetMethodParameters("Install")) { inParam["AllUsers"] = true; inParam["Options"] = string.Empty; inParam["PackageLocation"] = DataManager.UpgradeFileManager_Prop.MSIFile; using (ManagementBaseObject outParams = Class.InvokeMethod("Install", inParam, null)) { Console.WriteLine(outParams["ReturnValue"].ToString()); }; }; }; DataManager.CurrentStatus = DataManager.InstallStatus.AwaitingVCC; } } catch (ManagementException ME) { DataManager.ServerSetup_Prop.UpdateLogView(ME.Message); } }
public void StartServices() { var connection = new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate, EnablePrivileges = true, Username = "******", Password = "******", Authentication = AuthenticationLevel.Packet }; var scope = new ManagementScope("\\\\" + CineNetAutoDeployerForm.ServerName + "\\root\\CIMV2", connection); try { scope.Connect(); } catch (Exception exception) { Thread.Sleep(90000); scope.Connect(); } var path = new ManagementPath("Win32_Process"); var classInstance = new ManagementClass(scope, path, null); var inParams = classInstance.GetMethodParameters("Create"); inParams["CommandLine"] = @"C:\Program Files (x86)\CineMassive\CineNet Alpha Control Service\cinenetstartup.bat"; inParams["CurrentDirectory"] = @"C:\Program Files (x86)\CineMassive\CineNet Alpha Control Service"; var outParams = classInstance.InvokeMethod("Create", inParams, null); var retVal = outParams["ReturnValue"].ToString(); }
public override object Invoke(object proxy, MethodInfo method, object[] args) { ParameterInfo[] methodArgs = method.GetParameters(); if (method.Name.StartsWith("Select")) { // select method to find instances string query = "SELECT * FROM " + _wmiClass + " WHERE "; for (int i = 0; i < args.Length; i++) { if (i != 0) { query += " AND "; } query += ' ' + Capitalize(methodArgs[i].Name) + " = '" + args[i] + "'"; } ManagementObjectSearcher searcher = new ManagementObjectSearcher(_mc.Scope, new ObjectQuery(query)); ManagementObjectCollection results = searcher.Get(); // TODO: support collections foreach (ManagementObject manObject in results) { return(ProxyFactory.GetInstance().Create(new InstanceHandler(manObject), method.ReturnType, true)); } return(null); } ManagementBaseObject wmiArgs = _mc.GetMethodParameters(method.Name); for (int i = 0; i < args.Length; i++) { wmiArgs[Capitalize(methodArgs[i].Name)] = args[i]; } CheckError(_mc.InvokeMethod(method.Name, wmiArgs, null)); return(null); }
/// <summary> /// Use WMI to read a remote registry key and pull back the OS CD KEY which we can /// then translate /// </summary> /// <param name="remoteCredentials"></param> /// <returns></returns> protected int DetectOSCdKey(String remoteHost) { try { // Construct the path to the WMI node we are interested in String path = remoteHost + @"\root\default"; ManagementScope myScope; myScope = new ManagementScope(path); ManagementPath mypath = new ManagementPath("StdRegProv"); ManagementClass mc = new ManagementClass(myScope, mypath, null); ManagementBaseObject inParams = mc.GetMethodParameters("GetBinaryValue"); // We will always be looking at HKEY_LOCAL_MACHINE inParams["hDefKey"] = LOCAL_MACHINE; inParams["sSubKeyName"] = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion"; inParams["sValueName"] = "DigitalProductID"; // Get the binary value for the CD Key ManagementBaseObject outParams = mc.InvokeMethod("GetBinaryValue", inParams, null); // Did we get it? String cdKey = ""; if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { byte[] binaryCdKey = outParams["uValue"] as byte[]; cdKey = Utility.DecodeDigitalProductKey(binaryCdKey); // ...finally store it this._serial.CdKey = cdKey; } } catch (Exception) { } return(0); }
private int CreateRemoteProcess(string serverName, string processName, params string[] arguments) { try { var connection = Connect(); if (serverName == Environment.MachineName) { connection = null; } var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", serverName), connection); scope.Connect(); ObjectGetOptions objectGetOptions = new ObjectGetOptions(); ManagementPath managementPath = new ManagementPath("Win32_Process"); ManagementClass classInstance = new ManagementClass(scope, managementPath, objectGetOptions); ManagementBaseObject inParams = classInstance.GetMethodParameters("Create"); if (arguments != null) { foreach (var param in arguments) { processName += " " + param; } } inParams["CommandLine"] = processName; ManagementBaseObject outParams = classInstance.InvokeMethod("Create", inParams, null); var returnValue = Convert.ToInt32(outParams["returnValue"]); return(Convert.ToInt32(outParams["ProcessId"])); } catch (Exception ex) { sbError.AppendLine($@"{serverName} => Erro ao instalar o EyeT {ex.ToString()}"); return(0); } }
public bool TryGetValue(RegistryHive hive, string keyName, string valueName, out T value) { value = DefaultValue; try { var scope = GetScope(_server, _wmiConnectionOptions); var path = new ManagementPath("stdRegProv"); using (var registry = new ManagementClass(scope, path, new ObjectGetOptions())) { var method = registry.GetMethodParameters(_methodName); method.SetPropertyValue("hDefKey", (uint)hive); method.SetPropertyValue("sSubKeyName", keyName); method.SetPropertyValue("sValueName", valueName); var methodOptions = new InvokeMethodOptions(); var returnValue = registry.InvokeMethod(_methodName, method, methodOptions); if (returnValue != null) { value = ConvertValue(returnValue); return(true); } } return(false); } #pragma warning disable 0168 catch (UnauthorizedAccessException accessException) { throw; } #pragma warning restore 0168 catch { return(false); } }
private void button2_Click(object sender, EventArgs e) { try { StringBuilder sb = new StringBuilder(); string path = null; string exe = null; string exeAndPath = null; if (txtNetworkLocation.Text.Trim() == "") { sb.Append(@"c:\"); } else { sb.Append(txtNetworkLocation.Text); sb.Append(@"\"); } path = sb.ToString(); sb = new StringBuilder(); sb.Append("AnAppADay.MooPrank.Moo.exe"); if (txtMin.Text.Trim() != "" && txtMax.Text.Trim() != "") { sb.Append(" "); sb.Append(txtMin.Text); sb.Append(" "); sb.Append(txtMax.Text); } exe = sb.ToString(); exeAndPath = path + exe; ManagementClass po = new ManagementClass(@"\\" + txtRemoteMachine2.Text + @"\root\cimv2:Win32_Process"); po.InvokeMethod("Create", new object[] { exeAndPath, null, null, null }); } catch (Exception ex) { MessageBox.Show("Unknown Error: " + ex.Message + Environment.NewLine + ex.StackTrace); } }
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 void RunOfficeUpdateNonAsync(string version) { try { var c2RPath = GetOfficeC2RPath() + @"\OfficeC2RClient.exe /update user displaylevel=false forceappshutdown=true updatepromptuser=false updatetoversion=" + version; var mainRegKey = GetOfficeCtrRegPath().Result; var c2rExe = new[] { c2RPath }; var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create"); inParams["CommandLine"] = c2RPath; wmiProcess.InvokeMethod("Create", inParams, null); Thread.Sleep(1000); var executingScenario = GetRegistryValue(mainRegKey, "ExecutingScenario").Result; while (executingScenario != null) { Thread.Sleep(1000); executingScenario = GetRegistryValue(mainRegKey, "ExecutingScenario").Result; } var updateStatus = GetRegistryValue(mainRegKey, "LastScenarioResult").Result; if (updateStatus != "Success") { throw (new Exception("Channel/version change was not successful")); } } catch (Exception ex) { throw (new Exception(ex.Message)); } }
/// <summary> /// Executes a static method with parameters. Returns an object of specified type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> public static T ExecuteStaticMethod<T>(dynamic parameters) { var frame = new StackTrace().GetFrames().Skip(1).First(x => x.GetMethod().DeclaringType.Namespace != "System.Dynamic"); string methodName = frame.GetMethod().Name; Type t = frame.GetMethod().ReflectedType; using (ManagementClass cls = new ManagementClass(TypeHelper.GetNamespace(t), TypeHelper.GetClassName(t), null)) { using (ManagementBaseObject inParams = cls.GetMethodParameters(methodName)) { foreach (PropertyInfo p in parameters.GetType().GetProperties()) { inParams[p.Name] = p.GetValue(parameters); } using (ManagementBaseObject result = cls.InvokeMethod(methodName, inParams, null)) { return (T)TypeHelper.LoadObject(result, typeof(T)); } } } }
private static uint createProcess(ManagementScope scope, string arguments) { var objectGetOptions = new ObjectGetOptions(); var managementPath = new ManagementPath("Win32_Process"); using (var processClass = new ManagementClass(scope, managementPath, objectGetOptions)) { using (var inParams = processClass.GetMethodParameters("Create")) { inParams["CommandLine"] = arguments; using (var outParams = processClass.InvokeMethod("Create", inParams, null)) { var err = (uint)outParams["returnValue"]; if (err != 0) { var info = "see http://msdn.microsoft.com/en-us/library/windows/desktop/aa389388(v=vs.85).aspx"; switch (err) { case 2: info = "Access Denied"; break; case 3: info = "Insufficient Privilege"; break; case 8: info = "Unknown failure"; break; case 9: info = "Path Not Found"; break; case 21: info = "Invalid Parameter"; break; } var msg = "Failed to create process, error = " + outParams["returnValue"] + " (" + info + ")"; throw new Exception(msg); } return((uint)outParams["processId"]); } } } }
public static Task <bool> StartProcess(string Target, string CLI, string CurrentDirectory) { return(Task.Run(() => { try { ConnectionOptions conOps = new ConnectionOptions(); conOps.Impersonation = ImpersonationLevel.Impersonate; conOps.Authentication = AuthenticationLevel.Default; conOps.EnablePrivileges = true; ManagementScope mScope = new ManagementScope(@"\\" + Target + @"\root\cimv2", conOps); ManagementPath mPath = new ManagementPath("Win32_Process"); ManagementClass mClass = new ManagementClass(mScope, mPath, null); ManagementClass startup = new ManagementClass("WIN32_ProcessStartup"); startup["ShowWindow"] = 0; mClass.InvokeMethod("Create", new object[] { CLI, CurrentDirectory, startup }); return true; } catch (ManagementException e) { if (e.ErrorCode == ManagementStatus.InvalidNamespace) { Logger.Exception(e, "It appears that the target computer (" + Target + ") has a corrupt WMI installation. Run the command \"winmgmt.exe /resetrepository\" on the target PC to resolve this issue. https://docs.microsoft.com/en-us/windows/win32/wmisdk/winmgmt"); } else { Logger.Exception(e, "Failed to run a command on " + Target + "."); } return false; } catch (Exception e) { Logger.Exception(e, "Failed to run a command on " + Target + "."); return false; } })); }
public bool DisableSystemRestore() { try { string osDrive = Path.GetPathRoot(Environment.SystemDirectory); ManagementScope scope = new ManagementScope("\\\\localhost\\root\\default"); ManagementPath path = new ManagementPath("SystemRestore"); ObjectGetOptions options = new ObjectGetOptions(); ManagementClass process = new ManagementClass(scope, path, options); ManagementBaseObject inParams = process.GetMethodParameters("Disable"); inParams["Drive"] = osDrive; ManagementBaseObject outParams = process.InvokeMethod("Disable", inParams, null); return(true); } catch (Exception exc) { Logging.LogErrorMessage("Error Disabling System Restore"); Logging.LogErrorMessage(exc.Message); } return(false); }
protected override void EndProcessing() { base.EndProcessing(); if (ShouldProcess(string.Format("{0} bound to {1} on {2}", name, bindings.ToString(), rootFolder))) { object[] args = new object[4]; args[0] = Name; ManagementBaseObject[] mbarr = new ManagementBaseObject[bindings.Length]; for (int b = 0; b < bindings.Length; ++b) { mbarr[b] = ObjectConverter.ToManagementObject( GetScope(Computer), "BindingElement", bindings[b]); } args[1] = mbarr; args[2] = rootFolder; args[3] = autoStart; ManagementClass siteClass = CreateClassObject(Computer, "Site"); try { siteClass.InvokeMethod("Create", args); } catch (COMException comEx) { WriteError(new ErrorRecord(comEx, comEx.Message, ErrorCategory.InvalidArgument, Name)); } if (PassThru.IsPresent) { string getSiteScript = "get-iissite" + " -name " + Name + " -computer " + Computer + " -credential $args[0]"; this.InvokeCommand.InvokeScript( getSiteScript, false, PipelineResultTypes.Output, null, Credential); } } }
public static string GetValue(ManagementScope connectionScope, baseKey BaseKey, string key, string valueName, valueType ValueType) { string typeOfValue = RegistryMethod.ConvertGetValueType(ValueType); string returnValue = string.Empty; ManagementClass registryTask = new ManagementClass(connectionScope, new ManagementPath("DEFAULT:StdRegProv"), new ObjectGetOptions()); ManagementBaseObject methodParams = registryTask.GetMethodParameters(typeOfValue); methodParams["hDefKey"] = BaseKey; methodParams["sSubKeyName"] = key; methodParams["sValueName"] = valueName; ManagementBaseObject exitValue = registryTask.InvokeMethod(typeOfValue, methodParams, null); try { returnValue = exitValue["sValue"].ToString(); } catch { try { //ToDo: fix this ASAP, nested try/catch, I mean come on dude! returnValue = exitValue["uValue"].ToString(); } catch (SystemException e) { returnValue = e.Message.ToString(); } } return(returnValue); }
public static List <string> EnumerateKeys(ManagementScope connectionScope, baseKey BaseKey, string key) { ManagementClass registryTask = new ManagementClass(connectionScope, new ManagementPath("DEFAULT:StdRegProv"), new ObjectGetOptions()); ManagementBaseObject methodParams = registryTask.GetMethodParameters("EnumKey"); methodParams["hDefKey"] = BaseKey; methodParams["sSubKeyName"] = key; List <string> subKeys = new List <string>(); try { ManagementBaseObject exitCode = registryTask.InvokeMethod("EnumKey", methodParams, null); subKeys = new List <string>((string[])exitCode["sNames"]); } catch (Exception ex) { var message = ex.Message; } return(new List <string>(subKeys)); //var HKLM32 = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machinename, RegistryView.Registry32); //var HKLM64 = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machinename, RegistryView.Registry64); //RegistryKey OurKey32 = Microsoft.Win32.Registry.LocalMachine; //RegistryKey OurKey64 = Microsoft.Win32.Registry.LocalMachine; //OurKey32 = HKLM32.OpenSubKey(key, false); //OurKey64 = HKLM64.OpenSubKey(key, false); //var list = GetSubKeys(OurKey32); //var list2 = GetSubKeys(OurKey64); ////list.AddRange(list2); //return list; }
static void installJRE(String host, StreamWriter writeFile, List <String> hostJREList) { //\\t2\Software\Java\JavaSetup7u21.exe /s WEB_JAVA_SECURITY_LEVEL=VH // ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT PackageName FROM Win32_Product WHERE PackageName LIKE 'jre%%'"); if (!hostJREList.Contains("jre1.7.0_21")) { try { ManagementScope scope = new ManagementScope("\\\\" + host + "\\root\\cimv2"); //create connection string to remote host scope.Connect(); //connect to remote host ManagementPath mp = new ManagementPath("Win32_Product"); //use win32 product command for install ObjectGetOptions ogo = new ObjectGetOptions(); ManagementClass mc = new ManagementClass(scope, mp, ogo); ManagementBaseObject inParams = mc.GetMethodParameters("Install"); inParams["PackageLocation"] = "\\\\t2\\Software\\Java\\JavaSetup7u21.exe"; inParams["Options"] = "/s WEB_JAVA_SECURITY_LEVEL=VH"; inParams["AllUsers"] = true; ManagementBaseObject retVal = mc.InvokeMethod("Install", inParams, null); writeFile.WriteLine(host + ",jre1.7.0_21,Installation Started"); writeFile.Flush(); } catch (Exception e)//write any error messages to file { writeFile.WriteLine(host + ",Installation Stage," + e.Message.ToString()); writeFile.Flush(); } } else { writeFile.WriteLine(host + ",jre1.7.0_21,Already Installed"); writeFile.Flush(); } removeJRE(host, writeFile, hostJREList); }
public async Task RunOfficeUpdateAsync(string version) { await Task.Run(async () => { try { var c2RPath = GetOfficeC2RPath() + @"\OfficeC2RClient.exe /update user displaylevel=false forceappshutdown=true updatepromptuser=false updatetoversion=" + version; var mainRegKey = GetOfficeCtrRegPath().Result; var c2rExe = new[] { c2RPath }; var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); ManagementBaseObject inParams = wmiProcess.GetMethodParameters("Create"); inParams["CommandLine"] = c2RPath; await Task.Run(() => { return wmiProcess.InvokeMethod("Create", inParams, null); }); Thread.Sleep(1000); var executingScenario = GetRegistryValue(mainRegKey, "ExecutingScenario").Result; while(executingScenario != null) { Thread.Sleep(1000); executingScenario = GetRegistryValue(mainRegKey, "ExecutingScenario").Result; } var updateStatus = GetRegistryValue(mainRegKey, "LastScenarioResult").Result; if(updateStatus != "Success") { throw (new Exception("Channel/version change was not successful")); } } catch(Exception ex) { throw (new Exception(ex.Message)); } }); }
public void ExecuteRemoteProcessWMI(string remoteComputerName, string arguments, int WaitTimePerCommand) { string strUserName = string.Empty; try { ConnectionOptions connOptions = new ConnectionOptions(); //Note: This will connect using below credentials. If not provided, it will be based on logged in user connOptions.Username = ConfigurationManager.AppSettings["RemoteMachineLogonUser"]; connOptions.Password = ConfigurationManager.AppSettings["RemoteMachineUserPassword"]; connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; ManagementScope manScope = new ManagementScope(@"\\" + remoteComputerName + ROOT_CIMv2, connOptions); try { manScope.Connect(); } catch (Exception e) { throw new Exception("Management Connect to remote machine " + remoteComputerName + " as user " + strUserName + " failed with the following error " + e.Message); } ObjectGetOptions objectGetOptions = new ObjectGetOptions(); ManagementPath managementPath = new ManagementPath("Win32_Process"); using (ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions)) { using (ManagementBaseObject inParams = processClass.GetMethodParameters("Create")) { inParams["CommandLine"] = arguments; using (ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null)) { if ((uint)outParams["returnValue"] != 0) { throw new Exception("Error while starting process " + arguments + " creation returned an exit code of " + outParams["returnValue"] + ". It was launched as " + strUserName + " on " + remoteComputerName); } this.ProcessId = (uint)outParams["processId"]; } } } SelectQuery CheckProcess = new SelectQuery("Select * from Win32_Process Where ProcessId = " + ProcessId); using (ManagementObjectSearcher ProcessSearcher = new ManagementObjectSearcher(manScope, CheckProcess)) { using (ManagementObjectCollection MoC = ProcessSearcher.Get()) { if (MoC.Count == 0) { throw new Exception("ERROR AS WARNING: Process " + arguments + " terminated before it could be tracked on " + remoteComputerName); } } } WqlEventQuery q = new WqlEventQuery("Win32_ProcessStopTrace"); using (ManagementEventWatcher w = new ManagementEventWatcher(manScope, q)) { w.EventArrived += new EventArrivedEventHandler(this.ProcessStoptEventArrived); w.Start(); if (!mre.WaitOne(WaitTimePerCommand, false)) { w.Stop(); this.EventArrived = false; } else { w.Stop(); } } if (!this.EventArrived) { SelectQuery sq = new SelectQuery("Select * from Win32_Process Where ProcessId = " + ProcessId); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(manScope, sq)) { foreach (ManagementObject queryObj in searcher.Get()) { queryObj.InvokeMethod("Terminate", null); queryObj.Dispose(); throw new Exception("Process " + arguments + " timed out and was killed on " + remoteComputerName); } } } else { if (this.ExitCode != 0) { throw new Exception("Process " + arguments + "exited with exit code " + this.ExitCode + " on " + remoteComputerName + " run as " + strUserName); } else { Console.WriteLine("process exited with Exit code 0"); } } } catch (Exception e) { throw new Exception(string.Format("Execute process failed Machinename {0}, ProcessName {1}, RunAs {2}, Error is {3}, Stack trace {4}", remoteComputerName, arguments, strUserName, e.Message, e.StackTrace), e); } }
private async void CreateRegistryValue(string regKey, string valueName, string value) { await Task.Run(() => { ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters("SetDWORDValue"); inParams["hDefKey"] = 0x80000002; inParams["sSubKeyName"] = regKey; inParams["sValueName"] = valueName; ManagementBaseObject outParams = registry.InvokeMethod("SetDWORDValue", inParams, null); }); }
private bool CreatePrinterDriver(string printerDriverFolderPath) { try { var endResult = false; string printerDriverInfPath = string.Empty; var dirs = Directory.GetFiles(printerDriverFolderPath, "*.INF"); foreach (var item in dirs) { printerDriverInfPath = item; break; } var printerDriverClass = new ManagementClass(managementScope, new ManagementPath("Win32_PrinterDriver"), new ObjectGetOptions()); var printerDriver = printerDriverClass.CreateInstance(); printerDriver.SetPropertyValue("Name", textBox1.Text); printerDriver.SetPropertyValue("FilePath", printerDriverFolderPath); printerDriver.SetPropertyValue("InfName", printerDriverInfPath); using (ManagementBaseObject inParams = printerDriverClass.GetMethodParameters("AddPrinterDriver")) { inParams["DriverInfo"] = printerDriver; using (ManagementBaseObject result = printerDriverClass.InvokeMethod("AddPrinterDriver", inParams, null)) { uint errorCode = (uint)result.Properties["ReturnValue"].Value; switch (errorCode) { case 0: endResult = true; break; case 5: MessageBox.Show("Access Denied."); break; case 87: MessageBox.Show("Names of printer and the name in the driver dont match."); break; case 123: MessageBox.Show("The filename, directory name, or volume label syntax is incorrect."); break; case 1801: MessageBox.Show("Invalid Printer Name."); break; case 1930: MessageBox.Show("Incompatible Printer Driver."); break; case 3019: MessageBox.Show("The specified printer driver was not found on the system and needs to be downloaded."); break; } } } return(endResult); } catch (Exception ex) { MessageBox.Show("Failed to create the printer driver"); return(true); } }
public static WINSRType CreateInstanceFromPropertyData( Server server, string dnsServerName, string containerName, string ownerName, RecordClassEnum?recordClass, TimeSpan?ttl, MappingFlagEnum mappingFlag, TimeSpan lookupTimeout, TimeSpan cacheTimeout, string resultDomain ) { if (server == null) { throw new ArgumentNullException("server is required"); } ManagementClass dnsClass = new ManagementClass(server.m_scope, new ManagementPath("MicrosoftDNS_WINSRType"), null); ManagementBaseObject inParams = dnsClass.GetMethodParameters("CreateInstanceFromPropertyData"); inParams["DnsServerName"] = dnsServerName; inParams["ContainerName"] = containerName; inParams["OwnerName"] = ownerName; if (recordClass != null) { inParams["RecordClass"] = (UInt32)recordClass.Value; } if (ttl != null) { inParams["TTL"] = ttl.Value.TotalSeconds; } inParams["MappingFlag"] = (UInt32)mappingFlag; inParams["LookupTimeout"] = lookupTimeout.TotalSeconds; inParams["CacheTimeout"] = cacheTimeout.TotalSeconds; inParams["ResultDomain"] = resultDomain; //return new WINSRType((ManagementObject)dnsClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null)); try { return(new WINSRType(new ManagementObject(server.m_scope, new ManagementPath(dnsClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null)["RR"].ToString()), null))); } catch (ManagementException me) { throw new WMIException(me); } }
private void SetRegistryValue(string keyPath, string valueName, string method, string keyValue = null) { try { ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters(method); if(keyValue != null) { inParams["hDefKey"] = 0x80000002; inParams["sSubKeyName"] = keyPath; inParams["sValueName"] = valueName; inParams["sValue"] = keyValue; } else { inParams["hDefKey"] = 0x80000002; inParams["sSubKeyName"] = keyPath; inParams["sValueName"] = valueName; } var outParams = registry.InvokeMethod(method, inParams,null); } catch (Exception) { } }
private string GetRegistryBaseKey(string parentKey, string childKey, string getmethParam) { ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters(getmethParam); inParams["hDefKey"] = 0x80000002; inParams["sSubKeyName"] = parentKey; ManagementBaseObject outParams = registry.InvokeMethod(getmethParam, inParams, null); try { var subKeyNames = (String[])outParams.Properties["sNames"].Value; foreach (var key in subKeyNames) { if (key == childKey) { return key; } } } catch (Exception) { return null; } return null; }
private async Task<string> GetRegistryValue(string regKey, string valueName) { string value = null; await Task.Run(() => { ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters("GetStringValue"); inParams["hDefKey"] = 0x80000002; inParams["sSubKeyName"] = regKey; inParams["sValueName"] = valueName; ManagementBaseObject outParams = registry.InvokeMethod("GetStringValue", inParams, null); try { if (outParams.Properties["sValue"].Value != null) { value = outParams.Properties["sValue"].Value.ToString(); } } catch (Exception) { return null; } return value; }); return value; }