我可以在远程计算机上执行powershell命令,我可以执行powershell exchange snapin命令,但我无法弄清楚如何做到这两点。问题在于RunspaceFactory.CreateRunspace()
方法。
WSManConnectionInfo对象让我可以像这样定位远程主机:
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
new Uri(ConfigurationManager.AppSettings["ExchangeServerURI"]),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange",
new PSCredential(Username, secureString));
一个RunspaceConfugation + PSSnapInInfo让我像这样定位一个管理单元:
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
但我只能将一个或另一个提供给CreateRunspace()。它返回的Runtime对象具有ConnectionInfo和RunspaceConfiguration的属性,但它们都是readonly。这是一个有意的设计,您无法使用PowerShell管理程序远程执行代码,或者有没有办法做到这一点,我错过了?
答案 0 :(得分:0)
你可以做的一件事就是定义一个远程机器上的远程端点,它配置自己加载了所需的pssnapin,例如:
Register-PSSessionConfiguration -Name ExAdminShell -StartupScript InitScript.ps1
然后您将连接到该端点。
另一个想法是,如果您只是将Add-PSSnapin添加到您将要在远程计算机上运行的脚本的顶部,它是否会起作用?请记住,snapins是特定于位的,因此如果要连接到32位端点,则snapin最好是32位并注册。同样适用于64位管理单元。
答案 1 :(得分:0)
我最近遇到了同样的问题,即RunspaceFactory.CreateRunspace()构造函数只允许ConnectionInfo或RunspaceConfiguration参数而不是两者。我考虑了可选参数,但后来注意到这些属性只读。
我不知道是否可以肯定,仍在测试自己,但可能首先进行远程连接,然后在PowerShell运行空间下调用PSSnapIn可能会有效......
public static Collection<PSObject> remoteExchangePowerShell(string domain, string username, SecureString password, string remoteFQDNServer)
{
PSCredential remoteCredential = new PSCredential(string.Format("{0}\\{1}", domain, username), password);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(string.Format("http://{0}/Powershell?serializationLevel=Full", remoteFQDNServer)),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange", remoteCredential);
/*Just for PowerShell
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(string.Format("http://{0}/Powershell?serializationLevel=Full", remoteFQDNServer) + ":5985/wsman"),
"http://schemas.microsoft.com/powershell/Microsoft.PowerShell", remoteCredential);*/
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
//remoteRunspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
PSSnapInException psException;
powershell.Runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out psException);
....
}
}
}
我很想听听您的结果。