Search code examples
c#windowsbatch-fileexecute

Execute a batch on a remote computer with C# and show it on screen


When I start a batch on a remote computer using this code it runs perfectly. Only problem is, that the called script is not shown on screen. I would like to let the user know, that a program is running. And may read what is done by the used batch.

ConnectionOptions options = new ConnectionOptions();
options.Username = "user";
options.Password = "password";
options.EnablePrivileges = true;

ManagementScope scope = new ManagementScope($"{\\remotecomputer}\\root\\CIMV2", options);
scope.Connect();

ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass(scope, managementPath, objectGetOptions);

ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
inParams["CommandLine"] = "cmd /c e:\\tools\\batch.bat >> " + remoteOut + " 2>&1";

ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

as said it works great and generates the file "remoteOut" but the user does not see the batch running. Is there an possibility to set the "display" like on linux? I don't want to use ps command.

It runs the code, but the batch is not seen on screen.


Solution

  • You can't - at least, not using WMI directly.

    MS's documentation for Win32_Process.Create() states:

    For security reasons the Win32_Process.Create method cannot be used to start an interactive process remotely.


    There are workarounds, however - PsExec supports starting a process in an interactive session with the -i [session] command-line flag.

    You can start PsExec the usual way with ProcessStartInfo.