在具有不同凭据的远程PC上运行Powershell命令

时间:2013-11-20 21:12:50

标签: c# powershell exchange-server-2007

我需要弄清楚如何在安装了Exchange命令行管理程序的Exchange服务器上远程运行Exchange命令行管理程序命令。

1 个答案:

答案 0 :(得分:2)

此代码显示如何使用您想要的任何凭据打开与远程计算机的WSMan连接:

PSCredential credential = new PSCredential(someUserName, someSecurePassword);

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://targetmachinename:5985/wsman"), "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Negotiate;

using(Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))           
{
   ... use runspace here ...
}

现在,这将连接一个简单的PowerShell实例。如果要连接到Exchange就绪PowerShell实例,可以将Exchange shellUri指定为WSManConnectionInfo,您甚至不必担心添加管理单元:

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://targetmachinename:5985/wsman"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);