使用C#通过具有PowerShell的凭据将MSTSC导入远程桌面

时间:2018-10-27 03:39:53

标签: c# powershell pipeline runspace mstsc

我正在尝试使用如下脚本:

$Server="remotepc"

$User="user"

$Password="password"

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

在powershell中运行时效果很好。

我正在尝试使用C#中的运行空间和管道来获取它。

因此此代码有效:

 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();

但是,如果我使用用户名和密码添加脚本,它将停止工作并冻结。

因此此代码不起作用。

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();

1 个答案:

答案 0 :(得分:0)

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();
    }
}