MSTSC 使用 c# 使用 powershell 凭据进入远程桌面

MSTSC into remote desktop with credentials with powershell using c#

我正在尝试使用这样的脚本:

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

这对我有用。我认为您的 cmdkey 有错字。

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