Executing Powershell Commands against Exchange 2007 and Exchange 2010

The System.Management.Automation assembly allows the exeuction of Powershell commands against Exchange server.
Although, it would seem that the same code would be able to run for both of the versions of Exchange Server, two different codebases are required. The reason for this is that Exchange 2007 (SP1) supports only local Powershell, and Exchange 2010 uses remote Powershell.

The System.Management.Automation assembly allows the exeuction of Powershell commands against Exchange server.

Although, it would seem that the same code would be able to run for both of the versions of Exchange Server, two different codebases are required. The reason for this is that Exchange 2007 (SP1) supports only local powershell, and Exchange 2010 uses remote powershell.

 

        private void ConnectToExchange2007()
        {
            RunspaceConfiguration rc = RunspaceConfiguration.Create();
            PSSnapInException ex = null;
            PSSnapInInfo info = rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out ex);
            rs = RunspaceFactory.CreateRunspace(rc);
            Pipeline pl = rs.CreatePipeline();

            Command cmd = new Command("get-distributiongroup");
            pl.Commands.Add(cmd);
            ICollection<PSObject> results = pl.Invoke();
        }

        private const string SHELL_URI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
        private void ConnectToExchange2010()
        {
            WSManConnectionInfo connectionInfo = GetConnectionInfo(exchangeServer, userName, password);
            Runspace rs = RunspaceFactory.CreateRunspace(connectionInfo);
            PowerShell psh = PowerShell.Create();
            psh.Runspace = rs;
            rs.Open();

            psh.AddCommand("get-distributiongroup");
            Collection<PSObject> results = psh.Invoke();
        }

        private WSManConnectionInfo GetConnectionInfo(string servername, string username, string password)
        {
            System.Uri serveruri = new Uri(String.Format("http://{0}/powershell?serializationLevel=Full", servername));
            PSCredential creds;

            if (username.Length > 0 && password.Length > 0)
            {
                System.Security.SecureString securePassword = new System.Security.SecureString();
                foreach (char c in password.ToCharArray())
                {
                    securePassword.AppendChar(c);
                }
                creds = new PSCredential(username, securePassword);
            }
            else
            {
                // Use Windows Authentication
                creds = (PSCredential)null;
            }

            WSManConnectionInfo connectionInfo = new WSManConnectionInfo(serveruri, SHELL_URI, creds);
            return connectionInfo;
        }