Can not open EXE interactively while running PowerShell remotely using C#

54 Views Asked by At

I am trying to execute PowerShell command on remote machine using C# code. This command should launch notepad in the remote computer. I am facing two issues:

  1. While executing code, I can see process of notepad in Task Manager as running but I can't see window of notepad.
  2. While closing runspace in the code, the notepad also gets closed.

I used reference from here to write code.

 public PowerShellOutput RunRemotePowerShell(string computerName, string script)
 {
     AppConfig config = new AppConfig();
     PSCredential creds = CreateCredential(config.UserName, config.Password);
     Runspace runspace = GetRunSpace(computerName, creds);

     try
     {
         runspace.Open();

         using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
         {
             ps.Runspace = runspace;
             ps.AddScript(script);

             string results = PropOutput(ps.Invoke());  
             
             var errors = ps.Streams.Error;

             // in case of no error, errors will be empty.
             StringBuilder sbError = new StringBuilder();
             if (errors != null)
             {
                 foreach (var error in errors)
                 {
                     sbError.AppendLine(error.ToString());
                 }
             }

             string strError = sbError.ToString();
             PowerShellOutput objPSOutput = new PowerShellOutput();
             objPSOutput.PowerShellResult = results;    
             objPSOutput.PowerShellError = strError;

             return objPSOutput;

         }
     }

     //catch (PSRemotingTransportException ex)
     //{
     //    throw;
     //}

     catch
     {
         throw;
     }
     finally
     {
         if (runspace != null)
         {
             runspace.Close();
         }
     }
 }

 static void ExecuteExamples(string Script)
 {
Script = "Start-Process -FilePath notepad.exe"     
Console.WriteLine(Script);
     PowerShellHelper objRP = new PowerShellHelper();
     PowerShellOutput objPSOutput = new PowerShellOutput();
     objPSOutput = objRP.RunRemotePowerShell("RemoteComputerName", Script);
     Console.WriteLine(objPSOutput.PowerShellResult);
     Console.WriteLine(objPSOutput.PowerShellError);
     //Console.ReadLine();
 }
0

There are 0 best solutions below