我的代码完美运行:
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。