internal virtual Runspace OpenRunspace()
        {
            ExchangeLog.LogStart("OpenRunspace");

            if (runspaceConfiguration == null)
            {
                runspaceConfiguration = RunspaceConfiguration.Create();
                PSSnapInException exception = null;

                PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn(ExchangeSnapInName, out exception);

                if (exception != null)
                {
                    ExchangeLog.LogWarning("SnapIn error", exception);
                }
            }
            Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

            //AdminSessionADSettings adSettings = SetADSettings();
            runSpace.Open();
            //runSpace.SessionStateProxy.SetVariable("AdminSessionADSettings", adSettings);
            runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
            ExchangeLog.LogEnd("OpenRunspace");
            return(runSpace);
        }
        internal Collection <PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors)
        {
            ExchangeLog.LogStart("ExecuteShellCommand");
            List <object> errorList = new List <object>();

            ExchangeLog.DebugCommand(cmd);
            Collection <PSObject> results = null;
            // Create a pipeline
            Pipeline pipeLine = runSpace.CreatePipeline();

            using (pipeLine)
            {
                // Add the command
                pipeLine.Commands.Add(cmd);
                // Execute the pipeline and save the objects returned.
                results = pipeLine.Invoke();

                // Log out any errors in the pipeline execution
                // NOTE: These errors are NOT thrown as exceptions!
                // Be sure to check this to ensure that no errors
                // happened while executing the command.
                if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                {
                    foreach (object item in pipeLine.Error.ReadToEnd())
                    {
                        errorList.Add(item);
                        string errorMessage = string.Format("Invoke error: {0}", item.ToString());
                        ExchangeLog.LogWarning(errorMessage);
                    }

                    throw new Exception(errorList[0].ToString());
                }
            }
            pipeLine = null;
            errors   = errorList.ToArray();
            ExchangeLog.LogEnd("ExecuteShellCommand");
            return(results);
        }
        public ExchangeOrganization GetOrganizationDetails(string organizationId)
        {
            // get organization details
            ExchangeLog.LogStart("GetOrganizationDetails");
            ExchangeLog.DebugInfo("organizationId: {0}", organizationId);

            Runspace runSpace = null;

            try
            {
                runSpace = OpenRunspace();

                // create organization details object
                ExchangeOrganization org = new ExchangeOrganization {
                    Name = organizationId
                };

                #region Get organization details
                Collection <PSObject> result = GetOrganizationDetailsInternal(runSpace, organizationId);
                if (result.Count == 0)
                {
                    ExchangeLog.LogWarning("Organization '{0}' was not found", organizationId);
                    return(null);
                }

                PSObject objOrg = result[0];
                org.DistinguishedName = (string)GetPSObjectProperty(objOrg, "DistinguishedName");
                org.ServicePlan       = (string)GetPSObjectProperty(objOrg, "ServicePlan");
                org.ProgramId         = (string)GetPSObjectProperty(objOrg, "ProgramID");
                org.OfferId           = (string)GetPSObjectProperty(objOrg, "OfferID");
                #endregion

                #region Get organization quotas
                ExchangeLog.LogStart("Get-RecipientEnforcementProvisioningPolicy");

                Command cmd = new Command("Get-RecipientEnforcementProvisioningPolicy");
                cmd.Parameters.Add("Identity", String.Format("{0}\\{1}", organizationId, RecipientQuotaPolicyIdentity));

                // run command
                result = ExecuteShellCommand(runSpace, cmd);
                if (result.Count == 0)
                {
                    throw new NullReferenceException(String.Format("Recipient quota policy for organization '{0}' was not found", organizationId));
                }

                PSObject objQuota = result[0];
                //ExchangeLog.LogInfo(GetPSObjectProperty(objQuota, "MailboxCountQuota").GetType().ToString());
                org.MailboxCountQuota          = ConvertUnlimitedToInt32((Unlimited <Int32>)GetPSObjectProperty(objQuota, "MailboxCountQuota"));
                org.ContactCountQuota          = ConvertUnlimitedToInt32((Unlimited <Int32>)GetPSObjectProperty(objQuota, "ContactCountQuota"));
                org.DistributionListCountQuota = ConvertUnlimitedToInt32((Unlimited <Int32>)GetPSObjectProperty(objQuota, "DistributionListCountQuota"));

                ExchangeLog.LogEnd("Get-RecipientEnforcementProvisioningPolicy");
                #endregion

                #region Get organization statistics

                // mailboxes
                ExchangeLog.LogStart("Get-Mailbox");
                cmd = new Command("Get-Mailbox");
                cmd.Parameters.Add("Organization", organizationId);
                org.MailboxCount = ExecuteShellCommand(runSpace, cmd).Count;

                // remove system "DiscoverySearchMailbox" from statistics
                //if (org.MailboxCount > 0)
                //    org.MailboxCount -= 1;

                ExchangeLog.LogEnd("Get-Mailbox");

                // contacts
                ExchangeLog.LogStart("Get-Contact");
                cmd = new Command("Get-Contact");
                cmd.Parameters.Add("Organization", organizationId);
                org.ContactCount = ExecuteShellCommand(runSpace, cmd).Count;
                ExchangeLog.LogEnd("Get-Contact");

                // distribution lists
                ExchangeLog.LogStart("Get-DistributionGroup");
                cmd = new Command("Get-DistributionGroup");
                cmd.Parameters.Add("Organization", organizationId);
                org.DistributionListCount = ExecuteShellCommand(runSpace, cmd).Count;
                ExchangeLog.LogEnd("Get-DistributionGroup");
                #endregion

                #region Get domains
                org.Domains = GetOrganizationDomains(runSpace, organizationId).ToArray();
                #endregion

                #region Administrator e-mail
                ExchangeLog.LogStart("Get-RoleGroupMember");
                cmd = new Command("Get-RoleGroupMember");
                cmd.Parameters.Add("Identity", GetOrganizationManagementGroupDN(org.DistinguishedName));
                result = ExecuteShellCommand(runSpace, cmd);

                if (result.Count > 0)
                {
                    org.AdministratorName = (string)GetPSObjectProperty(result[0], "Name");
                    SmtpAddress adminEmail = (SmtpAddress)GetPSObjectProperty(result[0], "PrimarySmtpAddress");
                    org.AdministratorEmail = (adminEmail != null) ? adminEmail.ToString() : null;
                }
                ExchangeLog.LogEnd("Get-RoleGroupMember");
                #endregion

                ExchangeLog.LogEnd("GetOrganizationDetails");
                return(org);
            }
            finally
            {
                CloseRunspace(runSpace);
            }
        }