繁体   English   中英

使用C#执行远程交换Powershell命令

[英]Execute remote exchange powershell command with C#

我可以在远程计算机上执行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的属性,但它们都是只读的。 这是否是您无法通过Powershell管理单元远程执行代码的故意设计,还是有一种我所缺少的方法?

您可以做的一件事是定义一个远程端点(在远程计算机上),该端点将自身配置为加载所需的pssnapin,例如:

Register-PSSessionConfiguration -Name ExAdminShell -StartupScript InitScript.ps1

然后,您将连接到该端点。

换一种说法,如果仅将Add-PSSnapin添加到要在远程计算机上运行的脚本的顶部,这是行不通的吗? 请记住,管理单元是特定于位的,因此,如果您要连接到32位端点,则管理单元最好为32位并已注册。 同上64位管理单元。

最近,我遇到了相同的问题,即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);

                ....

            }
        }
    }

我很想听听您的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM