Glowhollow
Glowhollow

Reputation: 132

Executing Process on a remote Machine c#

i connected over WMI on a remote Machine.

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...

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 ?

Upvotes: 0

Views: 1015

Answers (1)

Ctznkane525
Ctznkane525

Reputation: 7465

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

Also you should redirect your output to a file using cmd as you should get your output directly either.

For script, make sure you use a unc that other machine/user has access to. For output file, make sure you use a unc that other machine/user can write to and you can read from via the program.

Upvotes: 1

Related Questions