在远程计算机c#上执行进程



i通过WMI连接到远程计算机上。

用户名和密码设置正确。

var options = new ConnectionOptions();
servicePath = "\\Testserver\root\cimv2";
options.EnablePrivileges = true;
options.Username = username;
options.Password = pwd;
serviceScope = new ManagementScope(servicePath, options);
serviceScope.Connect();

这是我想在远程机器上运行的代码序列

Process process = new Process();
process.StartInfo.FileName = "diskpart.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.StandardInput.WriteLine("list volume");
process.StandardInput.WriteLine("exit");
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// extract information from output
string table = output.Split(new string[] { "DISKPART>" }, StringSplitOptions.None)[1];
var rows = table.Split(new string[] { "n" }, StringSplitOptions.None);
for (int i = 3; i < rows.Length; i++)
{
if (rows[i].Contains("Volume"))
{
int index = Int32.Parse(rows[i].Split(new string[] { " " }, StringSplitOptions.None)[3]);
string label = rows[i].Split(new string[] { " " }, StringSplitOptions.None)[8];
Console.WriteLine($@"Volume {index} {label}:");
}
}

如果我要像这样通过wmi调用进程。。。

object[] theProcessToRun = { "diskpart" };
using (var managementClass = new ManagementClass(serviceScope, new ManagementPath("Win32_Process"), new ObjectGetOptions()))
{
managementClass.InvokeMethod("Create", theProcessToRun);
}

我可以调用进程,但不可能移交我想在此进程中执行的命令。。。

如何解决这个问题?

您可以使用一个脚本作为包含命令的命令行参数的一部分传入。

参考:https://www.computerhope.com/diskpart.htm

此外,您应该使用cmd将输出重定向到一个文件,因为您也应该直接获得输出。

对于脚本,请确保您使用其他机器/用户可以访问的unc。对于输出文件,请确保使用其他机器或用户可以写入和通过程序读取的unc。

最新更新