【问题标题】:MSTSC into remote desktop with credentials with powershell using c#MSTSC 使用 c# 使用带有 powershell 的凭据进入远程桌面
【发布时间】:2018-10-27 03:39:52
【问题描述】:

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

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

【问题讨论】:

  • "cmd/genaric:" - 通用

标签: c# powershell pipeline runspace mstsc


【解决方案1】:

这对我有用。我认为您的 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();
    }
}

【讨论】:

  • 行得通!感谢帮助。我猜有时只需要第二双眼睛。感谢您的帮助。
  • 如果您觉得有帮助,请接受我的回答并投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多