0

I'm connecting to an Exchange server for a remote powershell session, I have a code example below.

I do not want to hard code the "exchangeServerName" variable in case that box is ever offline, and I cannot run

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

because I would need to hard code a server name to be able to run that command. Any suggestions as to the best way to do this? I don't want to have to hard code anything.

Thanks!

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());
                    }
                }
            }
Bbb
  • 517
  • 6
  • 27
  • Have you investigated using AutoDiscover? – mjolinor Jan 21 '15 at 19:02
  • No I have not, do you have any code examples? – Bbb Jan 21 '15 at 19:25
  • Glen Scales has some powershell examples on his blog: http://gsexdev.blogspot.com/2012/01/ews-managed-api-and-powershell-how-to.html – mjolinor Jan 21 '15 at 19:45
  • Random side tidbit... If you are aiming for security you shouldn't hardcode the database username or password. look into using Azure Key Vault to programatically and securely request the creds on demand. – Kyle Bachmann Aug 08 '18 at 18:07

0 Answers0