建议连接远程PowerShell

时间:2015-01-21 18:57:26

标签: powershell powershell-v2.0 exchange-server exchange-server-2013

我正在连接到Exchange服务器以进行远程PowerShell会话,我在下面有一个代码示例。

我不想硬编码“exchangeServerName”变量,以防该框离线,我无法运行

Get-ExchangeServer | Where-Object {$_.IsMailboxServer -Eq $true -and $_.AdminDisplayVersion -Match "^Version 15" }  |  Select Name

因为我需要硬编码服务器名称才能运行该命令。有关最佳方法的建议吗?我不想硬编码任何东西。

谢谢!

string un = @"domain\username";
            System.Security.SecureString pw = new System.Security.SecureString();
            string password = "password";
            string databaseName = "databasename";
            string exchangeServerName = "http://exchangeserver.com/powershell";
            string microsoftSchemaName = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
            foreach (char ch in password)
            {
                pw.AppendChar(ch);
            }
            PSCredential cred = new PSCredential(un, pw);

            WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(exchangeServerName), microsoftSchemaName, cred);
            connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;

            using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
            {
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.AddCommand("Get-Mailboxdatabasecopystatus");
                    powershell.AddParameter("identity", databaseName);
                    powershell.AddCommand("select-object");
                    var props = new string[] { "name", "status" };
                    powershell.AddParameter("property", props);
                    runspace.Open();
                    powershell.Runspace = runspace;

                    Collection<PSObject> results = powershell.Invoke();

                    foreach (PSObject result in results)
                    {
                        MessageBox.Show(result.ToString());
                    }
                }
            }

0 个答案:

没有答案
相关问题