我需要在远程计算机上执行一个程序,所以我创建了一个服务来调用psexec(使用该服务很重要)。但是,此服务无法调用 psexec。
代码如下:
String cmd = "", arguments = "";
cmd = @"C:\PsTools\psexec.exe";
arguments = @"\\remoteComputer -u "user" -p "password" "C:\program.exe"";
Process process = new Process();
process.StartInfo.FileName = cmd;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
result = process.StandardOutput.ReadToEnd();
sError = process.StandardError.ReadToEnd();
result += "Program has finished its execution";
有谁知道为什么服务不能调用 psexec?
最佳答案
远程运行批处理文件时,我也遇到了 psexec 挂起的问题。 WMI 怎么样?在远程计算机上运行某些东西时,这对我有用;它也适用于 *.bat 和 *.exe。您可能需要单击“项目”>“添加引用”并在 .NET 选项卡上选择“System.Management”——在我手动添加之前,VS 2010 中不存在该引用。
System.Management.ConnectionOptions connOptions =
new System.Management.ConnectionOptions();
connOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
string compName = "RemoteComputerName";
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:\MyBatchFile.bat";
System.Management.ManagementBaseObject outParams =
processClass.InvokeMethod("Create", inParams, null);
关于c# - 在 C# 中使用服务执行 psexec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6507196/