簡體   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