Пример #1
0
        /// <summary>
        /// Add user to an AD group
        /// </summary>
        /// <param name="group_identity"></param>
        /// <param name="group_member"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel AddADGroupMember(string group_identity, string group_member)
        {
            try
            {
                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Add-ADGroupMember");
                    command.AddParameter("identity", group_identity);
                    command.AddParameter("member", group_member);
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                    return(successMessage);
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #2
0
        /// <summary>
        /// This method removes an existing AD group
        /// </summary>
        /// <param name="group_identity"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel RemoveADGroup(string group_identity)
        {
            UtilityController util = new UtilityController();

            try
            {
                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Remove-ADGroup");
                    command.AddParameter("identity", group_identity);
                    command.AddParameter("confirm", false);
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                    return(successMessage);
                }
            }
            catch (Exception e)
            {
                if (!e.Message.Contains(cantFindObjectError))
                {
                    return(util.ReportError(e));
                }
                return(util.ReportHiddenError(e));
            }
        }
Пример #3
0
        /// <summary>
        /// This method changes the surname of a user in AD.
        /// </summary>
        /// <param name="employeeid"></param>
        /// <param name="samaccountname"></param>
        /// <param name="field"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel ChangeUserValueDriver(string employeeid, string samaccountname, string field, string value)
        {
            try
            {
                if (value == "")
                {
                    value = null;
                }
                string   dName;
                PSObject user = util.getADUser(employeeid, samaccountname);
                if (user == null)
                {
                    throw new Exception("User was not found.");
                }
                dName = user.Properties["DistinguishedName"].Value.ToString();
                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Set-ADUser");
                    command.AddParameter("Identity", dName);
                    if (field.ToLower() == "ipphone")
                    {
                        if (value != null)
                        {
                            Hashtable attrHash = new Hashtable
                            {
                                { field, value }
                            };
                            command.AddParameter("replace", attrHash);
                        }
                        else
                        {
                            String[] attrArray = new String[1];
                            attrArray[0] = field;
                            command.AddParameter("clear", attrArray);
                        }
                    }
                    else
                    {
                        command.AddParameter(field, value);
                    }
                    command.AddParameter("ErrorVariable", "Err");
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                    return(successMessage);
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #4
0
        public MSActorReturnMessageModel ReportError(Exception e)
        {
            Debug.WriteLine("reporting an error");
            MSActorReturnMessageModel errorMessage = new MSActorReturnMessageModel("ERR", e.Message);

            Elmah.ErrorSignal.FromCurrentContext().Raise(e);
            return(errorMessage);
        }
Пример #5
0
        public MSActorReturnMessageModel ReportHiddenError(Exception e)
        {
            Debug.WriteLine("reporting a hidden error");
            MSActorReturnMessageModel SuccessMessage = new MSActorReturnMessageModel("CMP", e.Message);

            Elmah.ErrorSignal.FromCurrentContext().Raise(e);
            return(SuccessMessage);
        }
Пример #6
0
        public MSActorReturnMessageModel GetMoveRequest(string identity)
        {
            // Multiple paths to error
            MSActorReturnMessageModel errorMessage;

            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace())
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        ConnectToExchange(powershell, runspace);

                        PSCommand command = new PSCommand();
                        command.AddCommand("Get-MoveRequest");
                        command.AddParameter("Identity", identity);
                        powershell.Commands = command;
                        Collection <PSObject> existingMoveRequests = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            // Here we are throwing an error on purpose if a move request does not exist
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        string status = existingMoveRequests[0].Properties["Status"].Value.ToString() as string;
                        switch (status)
                        {
                        case "Completed":
                            MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                            return(successMessage);

                        case "InProgress":
                        case "Queued":
                            MSActorReturnMessageModel pendingMessage = new MSActorReturnMessageModel(PendingCode, "");
                            return(pendingMessage);

                        default:
                            string errorString = "Move request status is '" + status + "'";
                            errorMessage = new MSActorReturnMessageModel(ErrorCode, errorString);
                            Debug.WriteLine("ERROR: " + errorString);
                            return(errorMessage);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #7
0
        /// <summary>
        /// Delete entry for user
        /// </summary>
        /// <param name="employeeid"></param>
        /// <param name="samaccountname"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel RemoveADObject(string employeeid, string samaccountname)
        {
            UtilityController         util           = new UtilityController();
            MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");

            try
            {
                string   dName;
                PSObject user = util.getADUser(employeeid, samaccountname);
                if (user == null)
                {
                    return(successMessage);
                }
                Debug.WriteLine(user);
                dName = user.Properties["DistinguishedName"].Value.ToString();

                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Get-ADUser");
                    command.AddParameter("Identity", dName);
                    command.AddCommand("Get-ADObject");
                    command.AddCommand("Remove-ADObject");
                    command.AddParameter("confirm", false);
                    command.AddParameter("recursive");
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    return(successMessage);
                }
            }
            catch (Exception e)
            {
                if (!e.Message.Contains(cantFindObjectError))
                {
                    return(util.ReportError(e));
                }

                return(util.ReportHiddenError(e));
            }
        }
Пример #8
0
        /// <summary>
        /// ...
        /// </summary>
        /// <param name="employeeid"></param>
        /// <param name="samaccountname"></param>
        /// <param name="ipphone"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel SetIPPhone(string employeeid, string samaccountname, string ipphone)
        {
            UtilityController util = new UtilityController();

            try
            {
                string   dName;
                PSObject user = util.getADUser(employeeid, samaccountname);
                if (user == null)
                {
                    throw new Exception("User was not found.");
                }
                Debug.WriteLine(user);
                dName = user.Properties["DistinguishedName"].Value.ToString();

                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Get-ADUser");
                    command.AddParameter("Identity", dName);
                    command.AddCommand("Set-ADUser");
                    if (ipphone != null)
                    {
                        Hashtable ipPhoneHash = new Hashtable
                        {
                            { "ipPhone", ipphone }
                        };
                        command.AddParameter("replace", ipPhoneHash);
                    }
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                    return(successMessage);
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #9
0
        public MSActorReturnMessageModel NewDirectory(string computername, string path)
        {
            try
            {
                MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");

                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        command.AddCommand("New-Item");
                        command.AddParameter("ItemType", "directory");
                        command.AddParameter("Path", path);
                        powershell.Commands = command;
                        Collection <PSObject> returns = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].Exception.Message == String.Format("Item with specified name {0} already exists.", path))
                            {
                                return(successMessage);
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #10
0
        public MSActorReturnMessageModel SetMailboxQuotas(string identity, string prohibitsendreceivequota, string prohibitsendquota, string issuewarningquota)
        {
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace())
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        ConnectToExchange(powershell, runspace);

                        PSCommand command = new PSCommand();
                        command.AddCommand("Set-Mailbox");
                        command.AddParameter("Identity", identity);
                        command.AddParameter("IssueWarningQuota", issuewarningquota);
                        command.AddParameter("ProhibitSendQuota", prohibitsendquota);
                        command.AddParameter("ProhibitSendReceiveQuota", prohibitsendreceivequota);
                        command.AddParameter("UseDatabaseQuotaDefaults", false);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #11
0
        public MSActorReturnMessageModel ModifyDirQuota(string computername, string path, string limit)
        {
            // Project P0975: Replace old command line scripts with new PowerShell commands,
            // required after upgrading the Windows Server version on the file servers
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        command.AddCommand("Set-FsrmQuota");
                        command.AddParameter("Path", path);
                        command.AddParameter("Size", NumericLimit(limit));
                        powershell.Commands = command;
                        Collection <PSObject> result = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #12
0
 public MSActorReturnMessageModel AddUserFolderAccess(string employeeid, string samaccountname, string computername, string path, string accesstype)
 {
     try
     {
         PSObject user = util.getADUser(employeeid, samaccountname);
         if (user == null)
         {
             MSActorReturnMessageModel errorMessage = new MSActorReturnMessageModel(ErrorCode, "User was not found.");
             var customEx = new Exception("User was not found", new Exception());
             Elmah.ErrorSignal.FromCurrentContext().Raise(customEx);
             return(errorMessage);
         }
         else
         {
             string identity = user.Properties["SamAccountName"].Value as string;
             return(AddFolderAccess(identity, computername, path, accesstype));
         }
     }catch (Exception e)
     {
         return(util.ReportError(e));
     }
 }
Пример #13
0
        public MSActorReturnMessageModel RenameDirectory(string computername, string path, string newname)
        {
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        command.AddCommand("Rename-Item");
                        command.AddParameter("Path", path);
                        command.AddParameter("NewName", newname);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #14
0
        public MSActorReturnMessageModel HideMailboxFromAddressLists(string identity, string hidemailbox)
        {
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace())
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        ConnectToExchange(powershell, runspace);

                        // Now set the HiddenFromAddressListsEnabled flag
                        PSCommand command = new PSCommand();
                        command.AddCommand("Set-Mailbox");
                        command.AddParameter("Identity", identity);
                        command.AddParameter("HiddenFromAddressListsEnabled", Boolean.Parse(hidemailbox));
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #15
0
        public MSActorReturnMessageModel EnableDistributionGroup(string identity, string path, string description, string info)
        {
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace())
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        ConnectToExchange(powershell, runspace);

                        PSCommand command = new PSCommand();
                        command.AddCommand("New-DistributionGroup");
                        command.AddParameter("Name", identity);
                        command.AddParameter("OrganizationalUnit", path);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #16
0
        /// <summary>
        /// Remove user from an AD group
        /// </summary>
        /// <param name="group_identity"></param>
        /// <param name="group_member"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel RemoveADGroupMember(string group_identity, string group_member)
        {
            string notAMemberMessage     = "The specified account name is not a member of the group";
            string objectNotFoundMessage = "Directory object not found";

            try
            {
                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Remove-ADGroupMember");
                    command.AddParameter("identity", group_identity);
                    command.AddParameter("member", group_member);
                    command.AddParameter("confirm", false);
                    powershell.Commands = command;
                    powershell.Invoke();

                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                    return(successMessage);
                }
            }
            catch (Exception e)
            {
                if (!e.Message.Contains(notAMemberMessage) && !e.Message.Contains(objectNotFoundMessage))
                {
                    return(util.ReportError(e));
                }
                return(util.ReportHiddenError(e));
            }
        }
Пример #17
0
        public MSActorReturnMessageModel NewMoveRequest(string identity, string targetdatabase)
        {
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace())
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        ConnectToExchange(powershell, runspace);

                        PSCommand command = new PSCommand();
                        command.AddCommand("Get-MoveRequest");
                        command.AddParameter("Identity", identity);
                        powershell.Commands = command;
                        Collection <PSObject> existingMoveRequests = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            RemoteException ex = powershell.Streams.Error[0].Exception as RemoteException;
                            // ManagementObjectNotFoundException is okay; it means there was not an existing move request
                            if (!ex.SerializedRemoteException.TypeNames.Contains("Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException"))
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        // If there already is a move request we need to figure out what to do about it
                        if (existingMoveRequests.Count > 0)
                        {
                            string moveRequestStatus = existingMoveRequests[0].Properties["Status"].Value.ToString();
                            if (moveRequestStatus != "Completed")
                            {
                                // Is the same move request in flight or are we conflicting with another one?
                                if (existingMoveRequests[0].Properties["TargetDatabase"].Value.ToString() == targetdatabase)
                                {
                                    MSActorReturnMessageModel pndMessage = new MSActorReturnMessageModel(PendingCode, "");
                                    return(pndMessage);
                                }
                                else
                                {
                                    MSActorReturnMessageModel errMessage = new MSActorReturnMessageModel(ErrorCode, "Request still exists to move this mailbox to a different database");
                                    return(errMessage);
                                }
                            }
                            else
                            // Remove the completed move request and go on to make a new one
                            {
                                command = new PSCommand();
                                command.AddCommand("Remove-MoveRequest");
                                command.AddParameter("Identity", identity);
                                command.AddParameter("Confirm", false);
                                powershell.Commands = command;
                                powershell.Invoke();
                                if (powershell.Streams.Error.Count > 0)
                                {
                                    throw powershell.Streams.Error[0].Exception;
                                }
                                powershell.Streams.ClearStreams();
                            }
                        }

                        command = new PSCommand();
                        command.AddCommand("New-MoveRequest");
                        command.AddParameter("Identity", identity);
                        command.AddParameter("TargetDatabase", targetdatabase);
                        command.AddParameter("BadItemLimit", 1000);
                        command.AddParameter("AcceptLargeDataLoss");
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].Exception.Message.Contains("is already in the target database"))
                            {
                                return(util.ReportHiddenError(powershell.Streams.Error[0].Exception));
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        else
                        {
                            MSActorReturnMessageModel pendingMessage = new MSActorReturnMessageModel(PendingCode, "");
                            return(pendingMessage);
                        }
                        // powershell.Streams.ClearStreams();  -- is unreachable here
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #18
0
        public MSActorReturnMessageModel RemoveNetShare(string name, string computername, string path)
        {
            MSActorReturnMessageModel successMessage;

            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        // First check that the share name is for the correct path
                        PSCommand command = new PSCommand();
                        string    script  = String.Format("net share {0}", name);
                        command.AddScript(script);
                        powershell.Commands = command;
                        Collection <PSObject> ret = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].FullyQualifiedErrorId == "NativeCommandError")
                            {
                                // If the share does not exist return success
                                if (powershell.Streams.Error[0].Exception.Message == "This shared resource does not exist.")
                                {
                                    successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                                    return(successMessage);
                                }
                                else
                                {
                                    StringBuilder msgBuilder = new StringBuilder();
                                    foreach (ErrorRecord errorRec in powershell.Streams.Error)
                                    {
                                        // Kludge to fix a weird bug with blank lines in the error output
                                        if (errorRec.CategoryInfo.ToString() == errorRec.Exception.Message)
                                        {
                                            msgBuilder.AppendLine();
                                        }
                                        else
                                        {
                                            msgBuilder.AppendLine(errorRec.Exception.Message);
                                        }
                                    }
                                    throw new Exception(msgBuilder.ToString());
                                }
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        // Find the first (hopefully only) line in the output with "Path" at the beginning
                        string pathResultLine = ret.First(x => (x.BaseObject as string).StartsWith("Path")).BaseObject as string;
                        // The output looks like "Path              D:\Users\srenker".
                        // The regular expression below separates this into groups.
                        // Meaning of the next regex (from left to right):
                        // 1. Save all the characters that are not blanks into a group. (\S+)
                        // 2. Skip over all characters that are blanks. \s+
                        // 3. Save all the other characters into a group, up to end of line. (.+)$
                        // It's done this way because the path may have a space embedded in the name.
                        // The @ before the string tells C# not to escape any characters before passing it
                        // to the regular expression processor.
                        GroupCollection groups = Regex.Match(pathResultLine, @"(\S+)\s+(.+)$").Groups;
                        // Group 2 (#3 above) is the path value.
                        string existingPath = groups[2].Value;
                        if (!String.Equals(path, existingPath, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new Exception(String.Format("Share '{0}' is for path '{1}', different than specified.", name, existingPath));
                        }

                        // Now delete the share
                        script = String.Format("net share {0} /delete", name);
                        command.AddScript(script);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].FullyQualifiedErrorId == "NativeCommandError")
                            {
                                StringBuilder msgBuilder = new StringBuilder();
                                foreach (ErrorRecord errorRec in powershell.Streams.Error)
                                {
                                    // Kludge to fix a weird bug with blank lines in the error output
                                    if (errorRec.CategoryInfo.ToString() == errorRec.Exception.Message)
                                    {
                                        msgBuilder.AppendLine();
                                    }
                                    else
                                    {
                                        msgBuilder.AppendLine(errorRec.Exception.Message);
                                    }
                                }
                                throw new Exception(msgBuilder.ToString());
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #19
0
        public MSActorReturnMessageModel AddNetShare(string name, string computername, string path)
        {
            MSActorReturnMessageModel successMessage;

            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        string    script  = String.Format("net share {0}={1} \"/GRANT:Everyone,Full\"", name, path);
                        command.AddScript(script);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].FullyQualifiedErrorId == "NativeCommandError")
                            {
                                // If the share already exists it might be okay (see "else" below). Otherwise this is an error.
                                if (powershell.Streams.Error[0].Exception.Message != "The name has already been shared.")
                                {
                                    StringBuilder msgBuilder = new StringBuilder();
                                    foreach (ErrorRecord errorRec in powershell.Streams.Error)
                                    {
                                        // Kludge to fix a weird bug with blank lines in the error output
                                        if (errorRec.CategoryInfo.ToString() == errorRec.Exception.Message)
                                        {
                                            msgBuilder.AppendLine();
                                        }
                                        else
                                        {
                                            msgBuilder.AppendLine(errorRec.Exception.Message);
                                        }
                                    }
                                    throw new Exception(msgBuilder.ToString());
                                }
                                else
                                {
                                    powershell.Streams.ClearStreams();

                                    // Check that the existing share has the same path
                                    command = new PSCommand();
                                    script  = String.Format("net share {0}", name);
                                    command.AddScript(script);
                                    powershell.Commands = command;
                                    Collection <PSObject> ret = powershell.Invoke();
                                    if (powershell.Streams.Error.Count > 0)
                                    {
                                        throw powershell.Streams.Error[0].Exception;
                                    }
                                    powershell.Streams.ClearStreams();

                                    // Find the first (hopefully only) line in the output with "Path" at the beginning
                                    string pathResultLine = ret.First(x => (x.BaseObject as string).StartsWith("Path")).BaseObject as string;
                                    if (pathResultLine == null)
                                    {
                                        // There was not a line in the output containing the path, so we assume we got an error message instead.
                                        string message = ret.First(x => (x.BaseObject as string).Length > 0).BaseObject as string;
                                        throw new Exception(message);
                                    }
                                    else
                                    {
                                        // The output looks like "Path              D:\Users\srenker".
                                        // The regular expression below separates this into groups.
                                        // Meaning of the next regex (from left to right):
                                        // 1. Save all the characters that are not blanks into a group. (\S+)
                                        // 2. Skip over all characters that are blanks. \s+
                                        // 3. Save all the other characters into a group, up to end of line. (.+)$
                                        // It's done this way because the path may have a space embedded in the name.
                                        // The @ before the string tells C# not to escape any characters before passing it
                                        // to the regular expression processor.
                                        GroupCollection groups = Regex.Match(pathResultLine, @"(\S+)\s+(.+)$").Groups;
                                        // Group 2 (#3 above) is the path value.
                                        string pathResult = groups[2].Value;
                                        if (pathResult == path)
                                        {
                                            successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                                            return(successMessage);
                                        }
                                        else
                                        {
                                            throw new Exception(String.Format("Share '{0}' already exists for a different path '{1}'.", name, pathResult));
                                        }
                                    }
                                }
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                            // powershell.Streams.ClearStreams();  -- is unreachable here
                        }

                        successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #20
0
        public MSActorReturnMessageModel DisableMailbox(string identity)
        {
            try
            {
                // For use later; there are multiple routes to success
                MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");

                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace())
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        ConnectToExchange(powershell, runspace);

                        // First check for mobile devices and remove them
                        PSCommand command = new PSCommand();
                        command.AddCommand("Get-MobileDevice");
                        command.AddParameter("Mailbox", identity);
                        powershell.Commands = command;
                        Collection <PSObject> mobileDevices = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            // Mailbox may already be gone
                            RemoteException ex = powershell.Streams.Error[0].Exception as RemoteException;
                            if (ex.SerializedRemoteException.TypeNames.Contains("Microsoft.Exchange.Management.AirSync.RecipientNotFoundException"))
                            {
                                return(successMessage);
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        foreach (PSObject device in mobileDevices)
                        {
                            string deviceIdentity = device.Properties["Identity"].Value.ToString();
                            command = new PSCommand();
                            command.AddCommand("Remove-MobileDevice");
                            command.AddParameter("Identity", deviceIdentity);
                            command.AddParameter("Confirm", false);
                            powershell.Commands = command;
                            powershell.Invoke();
                            if (powershell.Streams.Error.Count > 0)
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                            powershell.Streams.ClearStreams();
                        }

                        command = new PSCommand();
                        command.AddCommand("Disable-Mailbox");
                        command.AddParameter("Identity", identity);
                        command.AddParameter("Confirm", false);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #21
0
        /// <summary>
        /// Set password
        /// </summary>
        /// <param name="employeeid"></param>
        /// <param name="samaccountname"></param>
        /// <param name="accountpassword"></param>
        /// <param name="changepasswordatlogon"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel SetPassword(string employeeid, string samaccountname, string accountpassword, string changepasswordatlogon)
        {
            MSActorReturnMessageModel errorMessage;
            UtilityController         util = new UtilityController();

            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    // Try without the runspace stuff first
                    //Runspace runspace = RunspaceFactory.CreateRunspace();
                    //powershell.Runspace = runspace;
                    //runspace.Open();

                    PSObject user = util.getADUser(employeeid, samaccountname);
                    if (user == null)
                    {
                        throw new Exception("User was not found.");
                    }

                    PSCommand command = new PSCommand();
                    command.AddCommand("ConvertTo-SecureString");
                    command.AddParameter("String", accountpassword);
                    command.AddParameter("AsPlainText");
                    command.AddParameter("Force");
                    powershell.Commands = command;
                    Collection <PSObject> pwd = powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    if (pwd.Count != 1)
                    {
                        // This may not be reached anymore
                        throw new Exception("Unexpected return from creating password secure string.");
                    }

                    command = new PSCommand();
                    command.AddCommand("Set-ADAccountPassword");
                    command.AddParameter("Identity", user);
                    command.AddParameter("NewPassword", pwd[0]);
                    command.AddParameter("Reset");
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    command = new PSCommand();
                    command.AddCommand("Set-AdUser");
                    command.AddParameter("Identity", user);
                    command.AddParameter("ChangePasswordAtLogon", Boolean.Parse(changepasswordatlogon));
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                    return(successMessage);
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #22
0
        public MSActorReturnMessageModel SetMailboxName(string identity, string alias, string addemailaddress)
        {
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace())
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        ConnectToExchange(powershell, runspace);

                        // Check that new alias does not already exist
                        PSCommand command = new PSCommand();
                        command.AddCommand("Get-Mailbox");
                        command.AddParameter("Identity", alias);
                        powershell.Commands = command;
                        Collection <PSObject> existingMailboxes = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            // It's okay if the object is not found
                            RemoteException ex = powershell.Streams.Error[0].Exception as RemoteException;
                            if (!ex.SerializedRemoteException.TypeNames.Contains("Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException"))
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        if (existingMailboxes.Any(x => (x.BaseObject as Mailbox)?.Alias == alias))
                        {
                            throw new Exception("Mailbox for new alias already exists.");
                        }

                        command = new PSCommand();
                        command.AddCommand("Set-Mailbox");
                        command.AddParameter("Identity", identity);
                        command.AddParameter("Alias", alias);
                        if (addemailaddress != null)
                        {
                            Hashtable emailaddresses = new Hashtable
                            {
                                { "add", addemailaddress }
                            };
                            command.AddParameter("EmailAddresses", emailaddresses);
                        }
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #23
0
        /// <summary>
        /// This method creates a new AD group
        /// </summary>
        /// <param name="group_name"></param>
        /// <param name="group_description"></param>
        /// <param name="group_info"></param>
        /// <param name="group_ad_path"></param>
        /// <param name="group_category"></param>
        /// <param name="group_scope"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel NewADGroup(string group_name, string group_description, string group_info,
                                                    string group_ad_path, string group_category, string group_scope, string samaccountname)
        {
            UtilityController util = new UtilityController();

            try
            {
                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command;

                    if (group_category == "distribution")
                    {
                        // First we need Exchange to enable the distribution group
                        ExchangeController        control = new ExchangeController();
                        MSActorReturnMessageModel msg     = control.EnableDistributionGroup(group_name, group_ad_path, group_description, group_info);
                        if (msg.code == "CMP")
                        {
                            // Then we follow up setting some attributes that Exchange's cmdlet won't set
                            string distinguishedName = "CN=" + group_name + "," + group_ad_path;

                            bool   setADGroupComplete = false;
                            int    count = 0;
                            string objectNotFoundMessage = "Directory object not found";
                            while (setADGroupComplete == false && count < 3)
                            {
                                try
                                {
                                    command = new PSCommand();
                                    command.AddCommand("Set-ADGroup");
                                    command.AddParameter("identity", distinguishedName);
                                    if (group_description != "")
                                    {
                                        command.AddParameter("description", group_description);
                                    }
                                    command.AddParameter("displayname", group_name);
                                    if (group_info != "")
                                    {
                                        Hashtable attrHash = new Hashtable
                                        {
                                            { "info", group_info }
                                        };
                                        command.AddParameter("Add", attrHash);
                                    }
                                    powershell.Commands = command;
                                    powershell.Invoke();
                                    if (powershell.Streams.Error.Count > 0)
                                    {
                                        if (powershell.Streams.Error[0].Exception.Message.Contains(objectNotFoundMessage))
                                        {
                                            System.Threading.Thread.Sleep(1000);
                                        }
                                        else
                                        {
                                            throw powershell.Streams.Error[0].Exception;
                                        }
                                    }
                                    else
                                    {
                                        setADGroupComplete = true;
                                    }
                                    count++;
                                }
                                catch (Exception e)
                                {
                                    if (e.Message.Contains(objectNotFoundMessage))
                                    {
                                        System.Threading.Thread.Sleep(1000);
                                        count++;
                                    }
                                    else
                                    {
                                        throw e;
                                    }
                                }
                            }
                            if (count == 3)
                            {
                                throw new Exception("Retry count exceeded. May indicate distribution group creation issue");
                            }
                            else
                            {
                                return(new MSActorReturnMessageModel(SuccessCode, ""));
                            }
                        }
                        else
                        {
                            return(msg);
                        }
                    }

                    command = new PSCommand();
                    command.AddCommand("New-ADGroup");
                    command.AddParameter("name", group_name);
                    if (group_description != "")
                    {
                        command.AddParameter("description", group_description);
                    }
                    command.AddParameter("groupcategory", group_category);
                    command.AddParameter("displayname", group_name);
                    command.AddParameter("path", group_ad_path);
                    command.AddParameter("groupscope", group_scope);
                    if (group_info != "")
                    {
                        Hashtable attrHash = new Hashtable
                        {
                            { "info", group_info }
                        };
                        command.AddParameter("OtherAttributes", attrHash);
                    }
                    command.AddParameter("samaccountname", samaccountname);
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();


                    MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                    return(successMessage);
                }
            }
            catch (Exception e)
            {
                if (!e.Message.Contains(groupExistsError))
                {
                    return(util.ReportError(e));
                }
                return(util.ReportHiddenError(e));
            }
        }
Пример #24
0
        private MSActorReturnMessageModel AddFolderAccess(string identity, string computername, string path, string accesstype)
        {
            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        // Note: The commands stacked on top of each other (prior to invoking) below have the effect
                        // of piping the output of one into the other, e.g. the result of Get-Acl becomes an input to Set-Variable.
                        // We need to work this way on a remote session so that type information does not get changed by
                        // retrieving the objects back to the local session.

                        PSCommand command = new PSCommand();
                        command.AddCommand("Get-Acl");
                        command.AddParameter("Path", path);
                        command.AddCommand("Set-Variable");
                        command.AddParameter("Name", "acl");
                        powershell.Commands = command;
                        Collection <PSObject> result = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        command = new PSCommand();
                        command.AddCommand("New-Object");
                        command.AddParameter("TypeName", "System.Security.AccessControl.FileSystemAccessRule");
                        command.AddParameter("ArgumentList",
                                             new object[]
                        {
                            identity,
                            accesstype,
                            "ContainerInherit,ObjectInherit",
                            "None",
                            "Allow"
                        });
                        command.AddCommand("Set-Variable");
                        command.AddParameter("Name", "perms");
                        powershell.Commands = command;
                        result = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        command = new PSCommand();
                        command.AddScript("$acl.SetAccessRule($perms)");
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        command = new PSCommand();
                        command.AddScript(String.Format("Set-Acl -AclObject $acl -Path {0}", path));
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #25
0
        /// <summary>
        /// ...
        /// </summary>
        /// <param name="employeeid"></param>
        /// <param name="searchbase"></param>
        /// <param name="old_samaccountname"></param>
        /// <param name="new_samaccountname"></param>
        /// <param name="userprincipalname"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel ChangeUsername(string employeeid, string old_samaccountname, string new_samaccountname, string userprincipalname)
        {
            UtilityController util = new UtilityController();

            try
            {
                // debugging:
                // $user = Get-ADUser -Filter "employeeid -eq '9999998'" -SearchBase 'OU=Accounts,DC=spudev,DC=corp' -Properties cn,displayname,givenname,initials
                // $userDN =$($user.DistinguishedName)
                // Set - ADUser - identity $userDN - sAMAccountName ‘wclinton’ -UserPrincipalName ‘wclinton @spudev.corp’  -ErrorVariable Err

                string   dName;
                PSObject user = util.getADUser(employeeid, old_samaccountname);
                if (user == null)
                {
                    throw new Exception("User was not found.");
                }
                Debug.WriteLine(user);
                dName = user.Properties["DistinguishedName"].Value.ToString();

                using (PowerShell powershell = PowerShell.Create())
                {
                    PSCommand command = new PSCommand();
                    command.AddCommand("Get-ADUser");
                    command.AddParameter("Identity", dName);
                    command.AddCommand("Set-Variable");
                    command.AddParameter("Name", "user");
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    command = new PSCommand();
                    command.AddScript("$($user.DistinguishedName)");
                    command.AddCommand("Set-Variable");
                    command.AddParameter("Name", "userDN");
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    command = new PSCommand();
                    command.AddScript(String.Format("Set-ADUser -Identity $userDN -sAMAccountName {0} -UserPrincipalName {1} -ErrorVariable Err", new_samaccountname, userprincipalname));
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    command = new PSCommand();
                    command.AddScript(String.Format("Rename-ADObject -Identity $userDN -NewName {0}", new_samaccountname));
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                    return(successMessage);
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #26
0
        public MSActorReturnMessageModel AddDirQuota(string computername, string path, string limit)
        {
            // Project P0975: Replace old command line scripts with new PowerShell commands,
            // required after upgrading the Windows Server version on the file servers
            MSActorReturnMessageModel successMessage;

            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        command.AddCommand("New-FsrmQuota");
                        command.AddParameter("Path", path);
                        command.AddParameter("Size", NumericLimit(limit));
                        powershell.Commands = command;
                        Collection <PSObject> result = powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            if (powershell.Streams.Error[0].Exception.Message.Trim() != "0x80045303, The specified object already exists.")
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                            else
                            {
                                powershell.Streams.ClearStreams();

                                // Check that the existing quota has the same limit
                                command = new PSCommand();
                                command.AddCommand("Get-FsrmQuota");
                                command.AddParameter("Path", path);
                                powershell.Commands = command;
                                Collection <PSObject> res = powershell.Invoke();
                                if (powershell.Streams.Error.Count > 0)
                                {
                                    throw powershell.Streams.Error[0].Exception;
                                }
                                CimInstance quota = (CimInstance)res.FirstOrDefault()?.BaseObject;
                                if ((ulong)quota.CimInstanceProperties["Size"].Value != NumericLimit(limit))
                                {
                                    throw new Exception("A different quota already exists on that folder");
                                }
                            }
                        }
                        powershell.Streams.ClearStreams();

                        successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #27
0
        public MSActorReturnMessageModel EnableMailbox(string database, string alias, string emailaddresses)
        {
            MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");

            try
            {
                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    using (Runspace runspace = RunspaceFactory.CreateRunspace())
                    {
                        runspace.Open();
                        powershell.Runspace = runspace;

                        ConnectToExchange(powershell, runspace);

                        PSCommand command = new PSCommand();
                        command.AddCommand("Enable-Mailbox");
                        command.AddParameter("identity", alias);
                        command.AddParameter("database", database);
                        command.AddParameter("alias", alias);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            // Check if the mailbox exists and is the way we want it
                            using (PowerShell powershell1 = PowerShell.Create())
                            {
                                powershell1.Runspace = runspace;
                                command = new PSCommand();
                                command.AddCommand("Get-Mailbox");
                                command.AddParameter("Identity", alias);
                                powershell1.Commands = command;
                                Collection <PSObject> mailboxes = powershell1.Invoke();
                                if (powershell1.Streams.Error.Count > 0)
                                {
                                    // If the mailbox is not found, fall through and throw the other exception.
                                    // Otherwise something is probably really wrong and throw this exception instead.
                                    RemoteException ex1 = powershell1.Streams.Error[0].Exception as RemoteException;
                                    if (!ex1.SerializedRemoteException.TypeNames.Contains("Microsoft.Exchange.Configuration.Tasks.ManagementObjectNotFoundException"))
                                    {
                                        throw powershell1.Streams.Error[0].Exception;
                                    }
                                }
                                Mailbox mailbox = mailboxes.FirstOrDefault()?.BaseObject as Mailbox;
                                if (mailbox != null &&
                                    mailbox.Database.Name == database &&
                                    mailbox.Alias == alias &&
                                    mailbox.EmailAddresses.Contains(ProxyAddress.Parse("SMTP", emailaddresses))
                                    )
                                {
                                    return(successMessage);
                                }
                                else
                                {
                                    throw powershell.Streams.Error[0].Exception;
                                }
                            }
                        }
                        powershell.Streams.ClearStreams();

                        command = new PSCommand();
                        command.AddCommand("set-mailbox");
                        command.AddParameter("identity", alias);
                        command.AddParameter("emailaddresses", emailaddresses);
                        powershell.Commands = command;
                        powershell.Invoke();
                        if (powershell.Streams.Error.Count > 0)
                        {
                            throw powershell.Streams.Error[0].Exception;
                        }
                        powershell.Streams.ClearStreams();

                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #28
0
        public MSActorReturnMessageModel RemoveDirectory(string computername, string path)
        {
            try
            {
                MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");

                PSSessionOption option = new PSSessionOption();
                using (PowerShell powershell = PowerShell.Create())
                {
                    string url = String.Format("http://{0}:5985/wsman", computername);
                    Uri    uri = new Uri(url);
                    WSManConnectionInfo conn = new WSManConnectionInfo(uri);
                    using (Runspace runspace = RunspaceFactory.CreateRunspace(conn))
                    {
                        powershell.Runspace = runspace;
                        runspace.Open();

                        PSCommand command = new PSCommand();
                        command.AddCommand("Remove-Item");
                        command.AddParameter("Path", path);
                        command.AddParameter("Recurse");
                        command.AddParameter("Force");
                        powershell.Commands = command;
                        powershell.Invoke();

                        if (powershell.Streams.Error.Count > 0)
                        {
                            RemoteException ex = powershell.Streams.Error[0].Exception as RemoteException;
                            if (ex.SerializedRemoteException.TypeNames.Contains("Deserialized.System.Management.Automation.ItemNotFoundException"))
                            {
                                return(successMessage);
                            }
                            else if (ex.SerializedRemoteException.TypeNames.Contains("Deserialized.System.IO.PathTooLongException"))
                            {
                                // Run our script for extra long paths instead
                                using (PowerShell powershell1 = PowerShell.Create())
                                {
                                    powershell1.Runspace = runspace;

                                    PSCommand command1 = new PSCommand();
                                    command1.AddCommand("Set-ExecutionPolicy");
                                    command1.AddParameter("ExecutionPolicy", "RemoteSigned");
                                    command1.AddParameter("Scope", "Process");
                                    command1.AddParameter("Force");
                                    powershell1.Commands = command1;
                                    powershell1.Invoke();
                                    if (powershell1.Streams.Error.Count > 0)
                                    {
                                        throw powershell1.Streams.Error[0].Exception;
                                    }
                                    powershell1.Streams.ClearStreams();

                                    command1 = new PSCommand();
                                    command1.AddScript(". D:\\PathTooLong.ps1");
                                    powershell1.Commands = command1;
                                    powershell1.Invoke();
                                    if (powershell1.Streams.Error.Count > 0)
                                    {
                                        throw powershell1.Streams.Error[0].Exception;
                                    }
                                    powershell1.Streams.ClearStreams();

                                    command1 = new PSCommand();
                                    command1.AddCommand("Remove-PathToLongDirectory");
                                    command1.AddArgument(path);
                                    powershell1.Commands = command1;
                                    powershell1.Invoke();
                                    if (powershell1.Streams.Error.Count > 0)
                                    {
                                        throw powershell1.Streams.Error[0].Exception;
                                    }
                                    powershell1.Streams.ClearStreams();
                                }
                            }
                            else
                            {
                                throw powershell.Streams.Error[0].Exception;
                            }
                        }
                        powershell.Streams.ClearStreams();

                        return(successMessage);
                    }
                }
            }
            catch (Exception e)
            {
                return(util.ReportError(e));
            }
        }
Пример #29
0
        /// <summary>
        /// This is a driver method to be called from the MSActorController. it creates a new user in AD, and returns
        /// the status message of the request.
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public MSActorReturnMessageModel NewADUserDriver(ADUserModel user)
        {
            // Project P0975: Update retry delays from 1 second to 3 seconds, attempting to
            // reduce error reports from delays in creating user accounts
            try
            {
                using (PowerShell powershell = PowerShell.Create())
                {
                    //Password nonsense to follow
                    PSCommand command = new PSCommand();
                    command.AddCommand("ConvertTo-SecureString");
                    command.AddParameter("AsPlainText");
                    command.AddParameter("String", user.accountPassword);
                    command.AddParameter("Force");
                    powershell.Commands = command;
                    Collection <PSObject> passHashCollection = powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();
                    PSObject toPass = passHashCollection.First();   //this is the password wrapped in a psobject

                    command = new PSCommand();
                    command.AddCommand("new-aduser");
                    command.AddParameter("name", user.name); //Name used to be emplid, but has since been changed
                    command.AddParameter("accountpassword", toPass);
                    command.AddParameter("changepasswordatlogon", user.changepasswordatlogon);
                    command.AddParameter("city", user.city);
                    //command.AddParameter("country", user.country);
                    command.AddParameter("department", user.department);
                    command.AddParameter("description", user.description);
                    command.AddParameter("displayname", user.displayname);
                    command.AddParameter("employeeid", user.employeeid);
                    command.AddParameter("enabled", user.enabled);
                    command.AddParameter("givenname", user.givenname);
                    command.AddParameter("officephone", user.officephone);
                    command.AddParameter("initials", user.initials);
                    command.AddParameter("office", user.office);
                    command.AddParameter("postalcode", user.postalcode);
                    command.AddParameter("samaccountname", user.samaccountname);
                    command.AddParameter("state", user.state);
                    command.AddParameter("streetaddress", user.streetaddress);
                    command.AddParameter("surname", user.surname);
                    command.AddParameter("Title", user.title);
                    command.AddParameter("type", user.type);
                    command.AddParameter("userprincipalname", user.userprincipalname);
                    command.AddParameter("path", user.path);
                    if (user.ipphone != null)
                    {
                        Hashtable attrHash = new Hashtable
                        {
                            { "ipPhone", user.ipphone }
                        };
                        command.AddParameter("OtherAttributes", attrHash);
                    }
                    powershell.Commands = command;
                    powershell.Invoke();
                    if (powershell.Streams.Error.Count > 0)
                    {
                        throw powershell.Streams.Error[0].Exception;
                    }
                    powershell.Streams.ClearStreams();

                    bool   adFinished            = false;
                    int    count                 = 0;
                    String objectNotFoundMessage = "Cannot find an object with identity";
                    while (adFinished == false && count < 6)
                    {
                        try
                        {
                            command = new PSCommand();
                            command.AddCommand("get-aduser");
                            command.AddParameter("identity", user.samaccountname);
                            powershell.Commands = command;
                            Collection <PSObject> check = powershell.Invoke();
                            if (powershell.Streams.Error.Count > 0)
                            {
                                if (powershell.Streams.Error[0].Exception.Message.Contains(objectNotFoundMessage))
                                {
                                    System.Threading.Thread.Sleep(3000);
                                }
                                else
                                {
                                    throw powershell.Streams.Error[0].Exception;
                                }
                            }
                            powershell.Streams.ClearStreams();
                            if (check.FirstOrDefault() != null)
                            {
                                adFinished = true;
                            }
                            count++;
                        }
                        catch (Exception e)
                        {
                            if (e.Message.Contains(objectNotFoundMessage))
                            {
                                System.Threading.Thread.Sleep(3000);
                                count++;
                            }
                            else
                            {
                                throw e;
                            }
                        }
                    }

                    if (count == 6)
                    {
                        throw new Exception("Retry count exceeded. May indicate account creation issue");
                    }
                }

                MSActorReturnMessageModel successMessage = new MSActorReturnMessageModel(SuccessCode, "");
                return(successMessage);
            }
            catch (Exception e)
            {
                if (!e.Message.Contains(accountExistsError))
                {
                    return(util.ReportError(e));
                }
                return(util.ReportHiddenError(e));
            }
        }