我的代码完美运行:
public static void RunTask(string[] task, string username, string password)
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(task[1] + ".exe");
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
string args = String.Format(@"-u {1} -p {2} -accepteula \\{0} " + (task[1] == "psexec" ? "-d -s -i 2 {3}" : "{3}"), task[0], username, password, task[1] == "psservice" ? task[2].TrimStart('"').Insert(task[2].IndexOf(' '), "\"") : task[2]);
psi.Arguments = args;
System.Diagnostics.Process prc = System.Diagnostics.Process.Start(psi);
string output = (prc.StandardError.ReadToEnd() + "\r\n" + prc.StandardOutput.ReadToEnd()).Trim();
output = output.Substring(output.IndexOf(".com\r\n\r\n") + 8);
prc.WaitForExit();
if (!(output.Contains("started on") || output.Contains("killed on") || output.Contains("SERVICE_NAME"))) throw new Exception(output);
}
示例调用:
RunTask(new string[] { "MACHINE", "psexec", @"""C:\Program Files (x86)\Internet Explorer\iexplore.exe""" }, "USERNAME", "PASSWORD");
RunTask(new string[] { "MACHINE", "pskill", @"""iexplore.exe""" }, "USERNAME", "PASSWORD");
RunTask(new string[] { "MACHINE", "psservice", @"""start SOMESERVICE""" }, "USERNAME", "PASSWORD");
RunTask(new string[] { "MACHINE", "psservice", @"""stop SOMESERVICE""" }, "USERNAME", "PASSWORD");
请确保在您的程序旁边有
psexec.exe、
pskill.exe和
psservice.exe文件。
psexec -i -s cmd.exe
命令来作为SYSTEM用户调用另一个CMD窗口,接着在第二个CMD窗口中粘贴和第一个CMD窗口完全相同的命令,就会重新出现这个错误。 - bill