Running Command Line in Remote Machine Using WMI

Recently I had to find a way for running a command line process in server. I had to spend fair bit of time googling for various approaches of doing it. Most of them are by using PSExec. However there is another approach of using WMI (Windows Management Instrumentation) . Below is one of the approach , which I found at msdn blog. Below method can be accessed anywhere by ProcessWMI p = new ProcessWMI(); p.ExecuteRemoteProcessWMI(remoteMachine, sBatFile, timeout); The solution has multiple parts as follows ...

September 8, 2018

Running Command Line from C#

Code Snippet private void RunCLIjobsOnLocal(string arguments, int WaitTimePerCommand) { var psi = new ProcessStartInfo(); psi.CreateNoWindow = true; //This hides the dos-style black window that the command prompt usually shows psi.FileName = @"cmd.exe"; psi.Arguments = "/C " + arguments; psi.RedirectStandardOutput = true; psi.RedirectStandardInput = true; psi.RedirectStandardError = true; psi.UseShellExecute = false; var sspw = new SecureString(); foreach (var c in password) { sspw.AppendChar(c); } psi.Domain = domain; psi.UserName = userName; psi.Password = sspw; psi.WorkingDirectory = @"C:\"; using (Process process = new Process()) { try { process.StartInfo = psi; process.Start(); var procId = process.Id; string owner = GetProcessOwner(procId); // Synchronously read the standard output of the spawned process. StreamReader reader = process.StandardOutput; string output = reader.ReadToEnd(); reader = process.StandardError; string error = reader.ReadToEnd(); if(error.Length >0) process.WaitForExit(); } catch (Exception e) { log.Error(e.Message + "\n" + e.StackTrace); } } } private string GetProcessOwner(int processId) { string query = "Select * From Win32_Process Where ProcessID = " + processId; ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementObjectCollection processList = searcher.Get(); foreach (ManagementObject obj in processList) { string[] argList = new string[] { string.Empty, string.Empty }; int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); if (returnVal == 0) { return argList[1] + "\\" + argList[0]; } } return "NO OWNER"; }

September 8, 2016