我正在尝试从C#启动一个MSTSC / RDP会话。出于各种原因,我决定调用Powershell来完成这个任务,部分原因是我知道powershell命令可以工作,尽管我不反对尝试其他方法来启动会话。我已经启用了RDSH,并且很高兴能够在这台机器上启动多个RDP会话。
在Powershell中运行以下命令将像我所期望的那样启动RDP会话:cmdkey /generic:TERMSRV/localhost /user:username /pass:password; mstsc /v:localhost
但是,试图使用下面的代码将其转换为C#的尝试失败了,但出现了以下错误:
指定的无效连接文件(True)
请注意,这是远程桌面连接错误,而不是powershell或C#错误。
我使用的代码是:
void StartRDP(string username, string password)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
// create cached credential to use for remote session
PowerShellInstance.AddCommand("cmdkey");
PowerShellInstance.AddParameter("/generic:TERMSRV/localhost");
PowerShellInstance.AddParameter("/user:" + username);
PowerShellInstance.AddParameter("/pass:" + password);
// append mstsc command
PowerShellInstance.AddStatement();
// start remote desktop connection to localhost
PowerShellInstance.AddCommand("mstsc");
PowerShellInstance.AddParameter("/v:localhost");
// invoke command, creating credential and starting mstsc
PowerShellInstance.Invoke();
}
}这称为使用:
StartRDP(username, password);
我还用硬编码变量进行了测试,结果也是一样的。任何建议都非常感谢!
编辑:检查了缓存在系统上的凭据,我可以看到这个方法在所有参数的末尾附加了"True“.请参见在Powershell中直接创建的凭据与在C#中创建的凭据之间的区别:
Powershell:
目标: LegacyGeneric:target=TERMSRV/localhost 类型:通用 用户:用户名
C#:
目标: LegacyGeneric:target=TERMSRV/localhost True 类型:通用 用户:用户名真
这似乎就是问题所在,尽管我离解决这个问题还差得很远。
发布于 2018-08-14 15:22:22
在进一步探讨了这个问题之后,我发现了这个问题;把这个答案留在这里,以防它将来对其他人有所帮助。
具有对象的参数以及参数(例如,/username user而不是/username)需要以这种格式提供PowerShell.AddParameter("user:","username")
这项经修订的守则适用于:
void StartRDP(string username, string password)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
// create cached credential to use for remote session
PowerShellInstance.AddCommand("cmdkey");
PowerShellInstance.AddParameter("generic","TERMSRV/localhost");
PowerShellInstance.AddParameter("user:",username);
PowerShellInstance.AddParameter("pass:",password);
// append mstsc command
PowerShellInstance.AddStatement();
// start remote desktop connection to localhost
PowerShellInstance.AddCommand("mstsc");
PowerShellInstance.AddParameter("/v","localhost");
// invoke command, creating credential and starting mstsc
PowerShellInstance.Invoke();
}
}https://stackoverflow.com/questions/51843893
复制相似问题