Code Snippet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
   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";
        }

Comments