简体   繁体   English

在远程计算机上执行过程C#

[英]Executing Process on a remote Machine c#

i connected over WMI on a remote Machine. 我通过远程计算机上的WMI连接。

username and password is correctly set. 用户名和密码设置正确。

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

this is the code sequence i want to run on the remote machine 这是我要在远程计算机上运行的代码序列

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}:\");
    }
}

if i am going to call the process over wmi like this... 如果我要像这样通过wmi调用进程...

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

i can call the process, but havent the possibilites to hand over the commands i would like to execute in this process... 我可以调用该过程,但没有可能移交我想在此过程中执行的命令...

How to solve this ? 如何解决呢?

You can use a script to be passed in as part of the command line arguments that will contain your command. 您可以使用脚本作为包含您的命令的命令行参数的一部分来传递。

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

Also you should redirect your output to a file using cmd as you should get your output directly either. 另外,您应该使用cmd将输出重定向到文件,因为您应该直接获取输出。

For script, make sure you use a unc that other machine/user has access to. 对于脚本,请确保使用其他计算机/用户有权访问的unc。 For output file, make sure you use a unc that other machine/user can write to and you can read from via the program. 对于输出文件,请确保使用其他机器/用户可以写入并可以通过该程序读取的unc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM