0

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

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

1 回答 1

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();
    }
}
于 2018-10-27T04:14:38.887 回答