Предложение для подключения с помощью удаленного PowerShell

Я подключаюсь к серверу 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 ответов

Другие вопросы по тегам