Search code examples
c#powershellpipelinerunspacemstsc

MSTSC into remote desktop with credentials with powershell using c#


I'm trying to use a script like this:

$Server="remotepc"

$User="user"

$Password="password"

cmdkey /generic:$Server /user:$User /pass:$Password
mstsc /v:$Server /console

which works fine when running in powershell.

I'm trying to get this using runspace and pipeline in c#.

So this code works:

 string server = "server";
 string mstscScript = "mstsc /v:"+server;

            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(mstscScript);


            pipeline.Invoke();

            runspace.Close();

However, if I add the script with the username and password it stops working and freezes.

So this code does not work.

string username = "user";
string password = "password";
string server = "server";


            string cmdScript="cmd/genaric:"+server+" /user:$" + username" + 
             /pass:$" + password;
            string mstscScript = "mstsc /v:" + server;

            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(cmdScript);
            pipeline.Commands.AddScript(mstscScript);


            pipeline.Invoke();

            runspace.Close();

Solution

  • This worked for me. I think your cmdkey has a typo.

    string tsScript = $"mstsc /v:{machinename}";
    string cmdKey = $"cmdkey /generic:{machinename} /user:{username} /pass:{password}";
    
    using (Runspace rs = RunspaceFactory.CreateRunspace())
    {
        rs.Open();
    
        using (Pipeline pl = rs.CreatePipeline())
        {
            pl.Commands.AddScript(cmdKey);
            pl.Commands.AddScript(tsScript);
            pl.Invoke();
        }
    }