//private char NULL_VALUE = char(0); public static ProcessReturnCode Run(string machineName, string commandLine, string args, string currentDirectory) { var connOptions = new ConnectionOptions { EnablePrivileges = true }; var scope = new ManagementScope(@"\\{0}\root\cimv2".FormatWith(machineName), connOptions); scope.Connect(); var managementPath = new ManagementPath(CLASSNAME); using (var processClass = new ManagementClass(scope, managementPath, new ObjectGetOptions())) { var inParams = processClass.GetMethodParameters("Create"); commandLine = System.IO.Path.Combine(currentDirectory, commandLine); inParams["CommandLine"] = "{0} {1}".FormatWith(commandLine, args); var outParams = processClass.InvokeMethod("Create", inParams, null); var rtn = Convert.ToUInt32(outParams["returnValue"]); var pid = Convert.ToUInt32(outParams["processId"]); if (pid != 0) { WaitForPidToDie(machineName, pid); } return (ProcessReturnCode)rtn; } }
//Create a system restore point using WMI. Should work in XP, VIsta and 7 private void buttonSystemRestore_Click(object sender, EventArgs e) { ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default"); ManagementPath oPath = new ManagementPath("SystemRestore"); ObjectGetOptions oGetOp = new ObjectGetOptions(); ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp); ManagementBaseObject oInParams = oProcess.GetMethodParameters("CreateRestorePoint"); oInParams["Description"] = "Nvidia PowerMizer Manager"; oInParams["RestorePointType"] = 10; oInParams["EventType"] = 100; this.buttonOK.Enabled = false; this.buttonCancel.Enabled = false; this.buttonSystemRestore.Enabled = false; this.labelDis.Text = "Creating System Restore Point. Please wait..."; ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null); this.buttonOK.Enabled = true; this.buttonCancel.Enabled = true; this.buttonSystemRestore.Enabled = true; this.labelDis.Text = text; }
/// <summary> /// Creates the share. /// </summary> /// <param name="FolderName">Name of the folder.</param> /// <param name="ShareName">Name of the share.</param> /// <param name="Description">The description.</param> /// <exception cref="System.Exception">Unable to share directory.</exception> public static void CreateShare(string FolderName, string ShareName, string Description ) { var RootPath = HostingEnvironment.ApplicationPhysicalPath; // Does folder exist? var StoreLocation = CreateFolder(FolderName, RootPath); ManagementClass managementClass = new ManagementClass("Win32_Share"); ManagementBaseObject inParams = managementClass.GetMethodParameters("Create"); ManagementBaseObject outParams; // Set the input parameters inParams["Description"] = Description; inParams["Name"] = ShareName; inParams["Path"] = StoreLocation; inParams["Type"] = ManagementType.DiskDrive; // Disk Drive //Another Type: // DISK_DRIVE = 0x0 // PRINT_QUEUE = 0x1 // DEVICE = 0x2 // IPC = 0x3 // DISK_DRIVE_ADMIN = 0x80000000 // PRINT_QUEUE_ADMIN = 0x80000001 // DEVICE_ADMIN = 0x80000002 // IPC_ADMIN = 0x8000003 //inParams["MaximumAllowed"] = int maxConnectionsNum; // Invoke the method on the ManagementClass object outParams = managementClass.InvokeMethod("Create", inParams, null); // Check to see if the method invocation was successful if ((uint) (outParams.Properties["ReturnValue"].Value) != 0) { throw new Exception("Unable to share directory."); } }
private bool SendCommand(string command, string username, string password) { Logger.EnteringMethod(command); try { ConnectionOptions connectoptions = new ConnectionOptions(); if (username != null && password != null && this.Name.ToLower() != GetFullyQualifiedDomainName().ToLower()) { connectoptions.Username = username; connectoptions.Password = password; } connectoptions.Impersonation = System.Management.ImpersonationLevel.Impersonate; System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", this.Name), connectoptions); mgmtScope.Connect(); System.Management.ObjectGetOptions objectGetOptions = new System.Management.ObjectGetOptions(); System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath("Win32_Process"); System.Management.ManagementClass processClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions); System.Management.ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup"); startupInfo.Properties["ShowWindow"].Value = 0; inParams["CommandLine"] = command; inParams["ProcessStartupInformation"] = startupInfo; processClass.InvokeMethod("Create", inParams, null); Logger.Write("Command Sent Successfuly on : " + this.Name); } catch (Exception ex) { Logger.Write("**** " + ex.Message); return(false); } return(true); }
public void Bob() { var connOptions = new ConnectionOptions { EnablePrivileges = true, //Username = "******", //Password = "******" }; string server = "SrvTestWeb01"; ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", server), connOptions); manScope.Connect(); var managementPath = new ManagementPath("Win32_Process"); var processClass = new ManagementClass(manScope, managementPath, new ObjectGetOptions()); var inParams = processClass.GetMethodParameters("Create"); inParams["CommandLine"] = @"C:\Temp\dropkick.remote\dropkick.remote.exe create_queue msmq://localhost/dk_test"; var outParams = processClass.InvokeMethod("Create", inParams, null); var rtn = System.Convert.ToUInt32(outParams["returnValue"]); var processID = System.Convert.ToUInt32(outParams["processId"]); }
public static void Shutdown(string mode) { if (mode == "WMI") { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // Get Security Privilages mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); //Option Flags mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } } else if (mode == "Core") { Process.Start("shutdown", "/s /t 0"); } }
public void Shutdown() { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); /* You can't shutdown without security privileges */ mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); /* 0 = Log off the network. * 1 = Shut down the system. * 2 = Perform a full reboot of the system. * 4 = Force any applications to quit instead of prompting the user to close them. * 8 = Shut down the system and, if possible, turn the computer off. */ /* Flag 1 means we want to shut down the system. Use "2" to reboot. */ mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
private static void ReportNow() { Logger.Write("Sending ReportNow."); try { ConnectionOptions connectoptions = new ConnectionOptions(); System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(@"\\.\ROOT\CIMV2", connectoptions); mgmtScope.Connect(); System.Management.ObjectGetOptions objectGetOptions = new System.Management.ObjectGetOptions(); System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath("Win32_Process"); System.Management.ManagementClass processClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions); System.Management.ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup"); startupInfo.Properties["ShowWindow"].Value = 0; inParams["CommandLine"] = "WuAuClt.exe /ReportNow"; inParams["ProcessStartupInformation"] = startupInfo; processClass.InvokeMethod("Create", inParams, null); } catch (Exception ex) { Logger.Write("Problem when doing ReportNow. " + ex.Message); } Logger.Write("ReportNow done."); }
public void AddARecord(string hostName, string zone, string iPAddress, string dnsServerName) { /*ConnectionOptions connOptions = new ConnectionOptions(); connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; connOptions.Username = "******"; connOptions.Password = "******"; */ ManagementScope scope = new ManagementScope(@"\\" + dnsServerName + "\\root\\MicrosoftDNS"); //,connOptions); scope.Connect(); ManagementClass wmiClass = new ManagementClass(scope, new ManagementPath("MicrosoftDNS_AType"), null); ManagementBaseObject inParams = wmiClass.GetMethodParameters("CreateInstanceFromPropertyData"); inParams["DnsServerName"] = dnsServerName; inParams["ContainerName"] = zone; inParams["OwnerName"] = hostName + "." + zone; inParams["IPAddress"] = iPAddress; wmiClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null); }
/// <summary> /// Creates the share. /// </summary> /// <param name="shareName">Name of the share.</param> /// <param name="folderPath">The folder path.</param> /// <returns>WindwsShare instance.</returns> public static WindowsShare CreateShare(string shareName, string folderPath) { ManagementClass shareClass = null; ManagementClass sd = null; ManagementBaseObject inParams = null; ManagementBaseObject outParams = null; try { sd = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null); sd["ControlFlags"] = 0x4; sd["DACL"] = new ManagementBaseObject[] { }; shareClass = new ManagementClass("Win32_Share"); inParams = shareClass.GetMethodParameters("Create"); inParams["Name"] = shareName; inParams["Path"] = new DirectoryInfo(folderPath).FullName; //// inParams["Description"] = description; inParams["Type"] = 0x0; // Type of Disk Drive inParams["Access"] = sd; outParams = shareClass.InvokeMethod("Create", inParams, null); if ((uint)outParams["ReturnValue"] != 0) { throw new WindowsShareException("Unable to create share. Win32_Share.Create Error Code: " + outParams["ReturnValue"]); } } catch (Exception ex) { throw new WindowsShareException("Unable to create share", ex); } finally { if (shareClass != null) { shareClass.Dispose(); } if (inParams != null) { inParams.Dispose(); } if (outParams != null) { outParams.Dispose(); } if (sd != null) { sd.Dispose(); } } return new WindowsShare(shareName); }
public static string StartProcess(string machineName, string processPath) { ManagementClass processTask = new ManagementClass(@"\\" + machineName + @"\root\CIMV2", "Win32_Process", null); ManagementBaseObject methodParams = processTask.GetMethodParameters("Create"); methodParams["CommandLine"] = processPath; ManagementBaseObject exitCode = processTask.InvokeMethod("Create", methodParams, null); return ProcessMethod.TranslateProcessStartExitCode(exitCode["ReturnValue"].ToString()); }
public override void Execute(object context = null) { ActionsHomeModel pc = context as ActionsHomeModel; //Can only be processed if the machine is online... if (pc.Status == ComputerStates.Online || pc.Status == ComputerStates.LoggedOn) { ManagementScope oMs = ConnectToClient(pc.Name); if (oMs != null) { this.DeleteQueryData(oMs, @"root\ccm\Policy", "SELECT * FROM CCM_SoftwareDistribution"); this.DeleteQueryData(oMs, @"root\ccm\Policy", "SELECT * FROM CCM_Scheduler_ScheduledMessage"); this.DeleteQueryData(oMs, @"root\ccm\Scheduler", "SELECT * FROM CCM_Scheduler_History"); //oMs.Path.NamespacePath = @"ROOT\CCM"; ManagementClass oClass = new ManagementClass(oMs, new ManagementPath("SMS_Client"), null); oClass.Get(); ManagementBaseObject inParams = oClass.GetMethodParameters("ResetPolicy"); inParams["uFlags"] = 1; oClass.InvokeMethod("ResetPolicy", inParams, new InvokeMethodOptions()); ManagementBaseObject newParams = oClass.GetMethodParameters("RequestMachinePolicy"); oClass.InvokeMethod("RequestMachinePolicy", newParams, new InvokeMethodOptions()); App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Completed; }), null); } else { App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Error; }), null); } } else { App.Current.Dispatcher.BeginInvoke(new Action(() => { this.State = RemoteActionState.Pending; }), null); } }
public static void CreateKey(ManagementScope connectionScope, baseKey BaseKey, string key) { ManagementClass registryTask = new ManagementClass(connectionScope, new ManagementPath("DEFAULT:StdRegProv"), new ObjectGetOptions()); ManagementBaseObject methodParams = registryTask.GetMethodParameters("CreateKey"); methodParams["hDefKey"] = BaseKey; methodParams["sSubKeyName"] = key; ManagementBaseObject exitCode = registryTask.InvokeMethod("CreateKey", methodParams, null); }
public static void ExitWindows(uint uFlags, uint dwReason) { ManagementBaseObject outParams = null; ManagementClass os = new ManagementClass("Win32_OperatingSystem"); os.Get(); os.Scope.Options.EnablePrivileges = true; // enables required security privilege. ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown"); inParams["Flags"] = uFlags.ToString(); inParams["Reserved"] = "0"; foreach (ManagementObject mo in os.GetInstances()) { outParams = mo.InvokeMethod("Win32Shutdown",inParams, null); } }
/// <summary> /// Shutdown the computer /// </summary> public static void Shutdown() { ManagementClass managementClass = new ManagementClass("Win32_OperatingSystem"); managementClass.Get(); managementClass.Scope.Options.EnablePrivileges = true; ManagementBaseObject methodParameters = managementClass.GetMethodParameters("Win32Shutdown"); methodParameters["Flags"] = "1"; methodParameters["Reserved"] = "0"; foreach (ManagementObject managementObject in managementClass.GetInstances()) { managementObject.InvokeMethod("Win32Shutdown", methodParameters, null); } }
private void MainWindow_Closed(object sender, EventArgs e) { if (MessageBox.Show("You must restart your computer to apply these changes.\nRestart now?", string.Empty, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { ManagementClass os = new ManagementClass("Win32_OperatingSystem"); os.Get(); os.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = os.GetMethodParameters("Win32Shutdown"); mboShutdownParams["Flags"] = "6"; mboShutdownParams["Reserved"] = "0"; ManagementBaseObject obj; foreach (ManagementObject instance in os.GetInstances()) obj = instance.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
public ManagementBaseObject RunCommand(Dictionary<string, string> inArgs) { // WMI: Use Win32_Process in root\cimv2 namespace. var processClass = new ManagementClass( new ManagementScope(String.Format(@"\\{0}\root\cimv2", this.hostName), this.connectionOptions), new ManagementPath("Win32_Process"), new ObjectGetOptions()); ManagementBaseObject parameters = processClass.GetMethodParameters("Create"); foreach (var item in inArgs) { parameters[item.Key] = item.Value; } return processClass.InvokeMethod("Create", parameters, null); }
public void ShutDownComputer(int flag) { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // You can't shutdown without security privileges mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system mboShutdownParams["Flags"] = flag; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
public static void Shutdown(ShutdownMode shutdownMode) { var mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // You can't shutdown without security privileges mcWin32.Scope.Options.EnablePrivileges = true; var mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system mboShutdownParams["Flags"] = ((int)shutdownMode).ToString(CultureInfo.InvariantCulture); mboShutdownParams["Reserved"] = "0"; foreach (var manObj in mcWin32.GetInstances().Cast<ManagementObject>()) { manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
public static 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; ManagementBaseObject exitCode = registryTask.InvokeMethod("EnumKey", methodParams, null); System.String[] subKeys; subKeys = (string[])exitCode["sNames"]; return subKeys; }
/* *Method that execute a WMI command on a remote computer and return all the profile folders' name * in an arraylist */ public static ArrayList getProfile(string computername) { //List to store the user profiles ArrayList profileList = new ArrayList(); //Line of the file written on the client string line; ConnectionOptions connOptions = new ConnectionOptions(); ObjectGetOptions objectGetOptions = new ObjectGetOptions(); ManagementPath managementPath = new ManagementPath("Win32_Process"); //To use caller credential connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", computername), connOptions); manScope.Connect(); InvokeMethodOptions methodOptions = new InvokeMethodOptions(null, System.TimeSpan.MaxValue); ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions); ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); //The command to execute to get the profile folder and write the result to C:\\tmp.txt inParams["CommandLine"] = "cmd /c " + "dir C:\\Users /B" + " > c:\\tmp.txt"; ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams,methodOptions); //Arbitratry delay to make sure that the command is done Thread.Sleep(2000); //Reading the result file StreamReader sr = new StreamReader("\\\\" + computername + "\\c$\\tmp.txt"); line = sr.ReadLine(); //While there are profile while (line != null) { //Add the profile to the arraylist profileList.Add(line); line = sr.ReadLine(); } sr.Close(); return profileList; }
private void button1_Click_1(object sender, EventArgs e) { System.Management.ConnectionOptions connOptions = new System.Management.ConnectionOptions(); connOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; connOptions.Username = "******"; connOptions.Password = "******"; string compName = "chan-PC"; System.Management.ManagementScope manScope = new System.Management.ManagementScope( String.Format(@"\\{0}\ROOT\CIMV2", compName), connOptions); manScope.Connect(); System.Management.ObjectGetOptions objectGetOptions = new System.Management.ObjectGetOptions(); System.Management.ManagementPath managementPath = new System.Management.ManagementPath("Win32_Process"); System.Management.ManagementClass processClass = new System.Management.ManagementClass(manScope, managementPath, objectGetOptions); System.Management.ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); inParams["CommandLine"] = @"c:\MalCode\hiWinForm.exe"; System.Management.ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null); var returnvalue = outParams["returnValue"]; if (outParams["returnValue"].ToString().Equals("0")) { MessageBox.Show("Process execution returned " + unchecked ((int)outParams["returnValue"])); } else { MessageBox.Show("No type specified " + unchecked ((int)outParams["returnValue"])); } }
public static bool ImportStore(string File) { bool IsMethodStatic = true; if ((IsMethodStatic == true)) { System.Management.ManagementBaseObject inParams = null; System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); System.Management.ManagementClass classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null); inParams = classObj.GetMethodParameters("ImportStore"); inParams["File"] = ((System.String)(File)); System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("ImportStore", inParams, null); return(System.Convert.ToBoolean(outParams.Properties["ReturnValue"].Value)); } else { return(System.Convert.ToBoolean(0)); } }
public static uint Disable(string Drive) { bool IsMethodStatic = true; if ((IsMethodStatic == true)) { System.Management.ManagementBaseObject inParams = null; System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); System.Management.ManagementClass classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null); inParams = classObj.GetMethodParameters("Disable"); inParams["Drive"] = ((System.String)(Drive)); System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("Disable", inParams, null); return(System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value)); } else { return(System.Convert.ToUInt32(0)); } }
internal static void ShutDownComputer() { FindAndKillProcess("Wow"); ManagementBaseObject outParameters = null; var sysOS = new ManagementClass("Win32_OperatingSystem"); sysOS.Get(); // enables required security privilege. sysOS.Scope.Options.EnablePrivileges = true; // get our in parameters ManagementBaseObject inParameters = sysOS.GetMethodParameters("Win32Shutdown"); // pass the flag of 0 = System Shutdown inParameters["Flags"] = "1"; inParameters["Reserved"] = "0"; foreach (ManagementObject manObj in sysOS.GetInstances()) { outParameters = manObj.InvokeMethod("Win32Shutdown", inParameters, null); } Environment.Exit(0); }
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; }
public static uint Restore(uint SequenceNumber) { bool IsMethodStatic = true; if ((IsMethodStatic == true)) { System.Management.ManagementBaseObject inParams = null; System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); System.Management.ManagementClass classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null); inParams = classObj.GetMethodParameters("Restore"); inParams["SequenceNumber"] = ((System.UInt32)(SequenceNumber)); System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("Restore", inParams, null); return(System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value)); } else { return(System.Convert.ToUInt32(0)); } }
private void Execute() { ConnectionOptions options = new ConnectionOptions(); if (!String.IsNullOrEmpty(textBoxPassword.Text) && !String.IsNullOrEmpty(textBoxUsername.Text)) { options.Username = String.Format("{0}\\{1}", textBoxHost.Text, textBoxUsername.Text); options.Password = textBoxPassword.Text; } try { Cursor = Cursors.WaitCursor; ManagementScope scope = new ManagementScope( String.Format("\\\\{0}\\root\\cimv2", textBoxHost.Text), options); scope.Connect(); ManagementClass win32ProcessClass = new ManagementClass("Win32_Process"); ManagementBaseObject inParameters = win32ProcessClass.GetMethodParameters("Create"); win32ProcessClass.Scope = scope; inParameters["CommandLine"] = textBoxExecute.Text; win32ProcessClass.InvokeMethod("Create", inParameters, null); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { Cursor = Cursors.Default; } }
/// <summary> /// Imports the assembly binding information file. /// </summary> /// <exception cref="BuildException"> /// <para>The assembly binding information file does not exist.</para> /// <para>-or-</para> /// <para>The assembly binding information file could not be imported.</para> /// </exception> protected override void ExecuteTask() { try { Log(Level.Verbose, "Importing bindings from \"{0}\"...", BindingFile.Name); // ensure assembly binding file exists if (!BindingFile.Exists) { throw new FileNotFoundException("Assembly binding information" + " file does not exist."); } ManagementPath path = new ManagementPath("MSBTS_DeploymentService"); ManagementClass deployClass = new ManagementClass(Scope, path, new ObjectGetOptions()); ManagementBaseObject inParams = deployClass.GetMethodParameters("Import"); inParams["Server"] = Server; inParams["Database"] = Database; // assembly binding information file inParams["Binding"] = BindingFile.FullName; // HTML log file to generate if (LogFile != null) { // ensure directory for log file exists if (!LogFile.Directory.Exists) { LogFile.Directory.Create(); LogFile.Directory.Refresh(); } inParams["Log"] = LogFile.FullName; } deployClass.InvokeMethod("Import", inParams, null); // log success Log(Level.Info, "Imported bindings from \"{0}\"", BindingFile.Name); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Assembly binding information file \"{0}\" could not be imported.", BindingFile.Name), Location, ex); } }
static void Main(string[] args) { try { CmdArgs parsedArgs = new CmdArgs(); if (!CommandLine.Parser.ParseArgumentsWithUsage(args, parsedArgs)) return; ConnectionOptions connOptions = new ConnectionOptions(); connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.Authentication = AuthenticationLevel.Default; connOptions.Username = parsedArgs.username; connOptions.Password = parsedArgs.password; connOptions.EnablePrivileges = true; ManagementScope scope = new ManagementScope(@"\\" + parsedArgs.machine + @"\root\cimv2", connOptions); scope.Connect(); ManagementPath mgmtPath = new ManagementPath("Win32_Process"); ManagementClass mgmtClass = new ManagementClass(scope, mgmtPath, null); ManagementBaseObject mgmtBaseObject = mgmtClass.GetMethodParameters("Create"); mgmtBaseObject["CommandLine"] = parsedArgs.command; ManagementBaseObject outputParams = mgmtClass.InvokeMethod("Create", mgmtBaseObject, null); uint pid = (uint) outputParams["processId"]; Console.Write("Pid: {0}", pid); SelectQuery sQuery = new SelectQuery("Win32_Process", string.Format("processId = {0}", pid)); ManagementObjectSearcher searcher = new ManagementObjectSearcher(sQuery); ManagementObjectCollection processes = null; while ((processes = searcher.Get()).Count > 0) { Console.Write("."); Thread.Sleep(1000); } Console.WriteLine(", done."); } catch (Exception ex) { Console.WriteLine("ERROR: {0}", ex.Message); } }
/// <summary> /// create client agents on nodes and start agents using WMI /// </summary> public static void CreateClientAgents() { Parallel.ForEach(TestEngine.TestPackage.Nodes.NodeList, node => { for (int i = 0; i < TestEngine.TestPackage.Nodes.NoOfClientsPerNode; i++) { string clientNumber = i.ToString(); //copy exe and other files to client location and start the exe string remoteServerName = node; if (!Directory.Exists(@"\\" + remoteServerName + @"\C$\WCFLoadUI" + clientNumber)) { Directory.CreateDirectory(@"\\" + remoteServerName + @"\C$\WCFLoadUI" + clientNumber); } foreach (string newPath in Directory.GetFiles(Environment.CurrentDirectory + @"\WCFService", "*.*", SearchOption.AllDirectories)) File.Copy(newPath, newPath.Replace(Environment.CurrentDirectory + @"\WCFService", @"\\" + remoteServerName + @"\C$\WCFLoadUI" + clientNumber), true); ConnectionOptions connectionOptions = new ConnectionOptions(); ManagementScope scope = new ManagementScope( @"\\" + remoteServerName + "." + Domain.GetComputerDomain().Name + @"\root\CIMV2", connectionOptions); scope.Connect(); ManagementPath p = new ManagementPath("Win32_Process"); ObjectGetOptions objectGetOptions = new ObjectGetOptions(); ManagementClass classInstance = new ManagementClass(scope, p, objectGetOptions); ManagementBaseObject inParams = classInstance.GetMethodParameters("Create"); inParams["CommandLine"] = @"C:\WCFLoadUI" + clientNumber + @"\WCFService.exe " + Environment.MachineName + " 9090"; inParams["CurrentDirectory"] = @"C:\WCFLoadUI" + clientNumber; classInstance.InvokeMethod("Create", inParams, null); } }); }
public static void Shutdown() { //http://stackoverflow.com/questions/102567/how-to-shutdown-the-computer-from-c-sharp ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // You can't shutdown without security privileges mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system. Use "2" to reboot. mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } }
public void SendCommand(string hostname, string command, Credential credential) { ConnectionOptions connectoptions = GetConnectionOptions(hostname, credential); connectoptions.Impersonation = System.Management.ImpersonationLevel.Impersonate; System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", hostname), connectoptions); mgmtScope.Connect(); System.Management.ObjectGetOptions objectGetOptions = new System.Management.ObjectGetOptions(); System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath("Win32_Process"); System.Management.ManagementClass processClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions); System.Management.ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup"); startupInfo.Properties["ShowWindow"].Value = 0; inParams["CommandLine"] = command; inParams["ProcessStartupInformation"] = startupInfo; processClass.InvokeMethod("Create", inParams, null); }
public static uint CreateRestorePoint(string Description, uint EventType, uint RestorePointType) { bool IsMethodStatic = true; if ((IsMethodStatic == true)) { System.Management.ManagementBaseObject inParams = null; System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); System.Management.ManagementClass classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null); inParams = classObj.GetMethodParameters("CreateRestorePoint"); inParams["Description"] = ((System.String)(Description)); inParams["EventType"] = ((System.UInt32)(EventType)); inParams["RestorePointType"] = ((System.UInt32)(RestorePointType)); System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("CreateRestorePoint", inParams, null); return(System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value)); } else { return(System.Convert.ToUInt32(0)); } }
private void launchButtonClicked(object sender, RoutedEventArgs e) { if (launchButton.IsEnabled == false) return; Settings s = GlobalAppData.settings; String executablePath = System.IO.Path.Combine(s.swgDirectory, s.executableName); GameProcess proc = new GameProcess(executablePath); using (var managementClass = new ManagementClass("Win32_Process")) { var processInfo = new ManagementClass("Win32_ProcessStartup"); processInfo.Properties["CreateFlags"].Value = 0x00000008; var inParameters = managementClass.GetMethodParameters("Create"); inParameters["CommandLine"] = executablePath; inParameters["ProcessStartupInformation"] = processInfo; var result = managementClass.InvokeMethod("Create", inParameters, null); if ((result != null) && ((uint)result.Properties["ReturnValue"].Value != 0)) { Console.WriteLine("Process ID: {0}", result.Properties["ProcessId"].Value); } } }
public static uint Create(string Description, string DfsEntryPath, string ServerName, string ShareName) { bool IsMethodStatic = true; if ((IsMethodStatic == true)) { System.Management.ManagementBaseObject inParams = null; System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); System.Management.ManagementClass classObj = new System.Management.ManagementClass(statMgmtScope, mgmtPath, null); inParams = classObj.GetMethodParameters("Create"); inParams["Description"] = ((System.String)(Description)); inParams["DfsEntryPath"] = ((System.String)(DfsEntryPath)); inParams["ServerName"] = ((System.String)(ServerName)); inParams["ShareName"] = ((System.String)(ShareName)); System.Management.ManagementBaseObject outParams = classObj.InvokeMethod("Create", inParams, null); return(System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value)); } else { return(System.Convert.ToUInt32(0)); } }
public static bool CreateUncShare(string shareName, string localPath) { ManagementScope scope = new System.Management.ManagementScope(@"root\CIMV2"); scope.Connect(); using (ManagementClass managementClass = new ManagementClass(scope, new ManagementPath("Win32_Share"), (ObjectGetOptions) null)) { SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, (SecurityIdentifier) null); byte[] binaryForm = new byte[securityIdentifier.BinaryLength]; securityIdentifier.GetBinaryForm(binaryForm, 0); using (ManagementObject wmiTrustee = new ManagementClass(scope, new ManagementPath("Win32_Trustee"), (ObjectGetOptions) null).CreateInstance()) { wmiTrustee["SID"] = (object) binaryForm; using (ManagementObject wmiACE = new ManagementClass(scope, new ManagementPath("Win32_ACE"), (ObjectGetOptions) null).CreateInstance()) { wmiACE["AccessMask"] = 131241; //READ_CONTROL | FILE_READ | FILE_TRAVERSE | FILE_READ_EA | FILE_LIST_DIRECTORY wmiACE["AceFlags"] = 3; //OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE wmiACE["AceType"] = 0; //ACCESS_ALLOWED wmiACE["Trustee"] = wmiTrustee; using (ManagementObject wmiSecurityDescriptor = new ManagementClass(scope, new ManagementPath("Win32_SecurityDescriptor"), (ObjectGetOptions) null).CreateInstance()) { wmiSecurityDescriptor["ControlFlags"] = 4; wmiSecurityDescriptor["DACL"] = new ManagementObject[] { wmiACE }; using (ManagementBaseObject inParamsCreate = managementClass.GetMethodParameters("Create")) { inParamsCreate["Access"] = wmiSecurityDescriptor; inParamsCreate["Path"] = localPath; inParamsCreate["Name"] = shareName; inParamsCreate["Type"] = 0; inParamsCreate["Description"] = "TVServerXBMC share"; using (ManagementBaseObject outParams = managementClass.InvokeMethod("Create", inParamsCreate, (InvokeMethodOptions) null)) return ((int) (uint) outParams["returnValue"] == 0); } } } } } }
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("[WMICLASSNAME]"); ManagementClass ClassInstance= new ManagementClass(Scope, Path, Options); ManagementBaseObject inParams = ClassInstance.GetMethodParameters("[WMIMETHOD]");
/// <summary> /// Shuts down the computer. /// </summary> /// <returns><c>true</c> if the computer was shut down successfully, or <c>false</c> otherwise.</returns> public static bool ShutDown() { try { ManagementClass os = new ManagementClass("Win32_OperatingSystem"); os.Get(); os.Scope.Options.EnablePrivileges = true; ManagementBaseObject parameters = os.GetMethodParameters("Win32Shutdown"); parameters["Flags"] = "1"; // Shut down parameters["Reserved"] = "0"; foreach (ManagementObject obj in os.GetInstances().Cast<ManagementObject>()) { obj.InvokeMethod("Win32Shutdown", parameters, null /* options */); } return true; } catch { return false; } }