/// <summary> /// Gets an array of commands that can be run sequentially to set $profile and run the profile commands. /// </summary> /// <param name="shellId">The id identifying the host or shell used in profile file names.</param> /// <param name="useTestProfile">used from test not to overwrite the profile file names from development boxes</param> /// <returns></returns> internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfile) { List<PSCommand> commands = new List<PSCommand>(); string allUsersAllHosts = HostUtilities.GetFullProfileFileName(null, false, useTestProfile); string allUsersCurrentHost = HostUtilities.GetFullProfileFileName(shellId, false, useTestProfile); string currentUserAllHosts = HostUtilities.GetFullProfileFileName(null, true, useTestProfile); string currentUserCurrentHost = HostUtilities.GetFullProfileFileName(shellId, true, useTestProfile); PSObject dollarProfile = HostUtilities.GetDollarProfile(allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost); PSCommand command = new PSCommand(); command.AddCommand("set-variable"); command.AddParameter("Name", "profile"); command.AddParameter("Value", dollarProfile); command.AddParameter("Option", ScopedItemOptions.None); commands.Add(command); string[] profilePaths = new string[] { allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost }; foreach (string profilePath in profilePaths) { if (!System.IO.File.Exists(profilePath)) { continue; } command = new PSCommand(); command.AddCommand(profilePath, false); commands.Add(command); } return commands.ToArray(); }
internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfile) { List <PSCommand> psCommandList = new List <PSCommand>(); string fullProfileFileName1 = HostUtilities.GetFullProfileFileName((string)null, false, useTestProfile); string fullProfileFileName2 = HostUtilities.GetFullProfileFileName(shellId, false, useTestProfile); string fullProfileFileName3 = HostUtilities.GetFullProfileFileName((string)null, true, useTestProfile); string fullProfileFileName4 = HostUtilities.GetFullProfileFileName(shellId, true, useTestProfile); PSObject dollarProfile = HostUtilities.GetDollarProfile(fullProfileFileName1, fullProfileFileName2, fullProfileFileName3, fullProfileFileName4); PSCommand psCommand1 = new PSCommand(); psCommand1.AddCommand("set-variable"); psCommand1.AddParameter("Name", (object)"profile"); psCommand1.AddParameter("Value", (object)dollarProfile); psCommand1.AddParameter("Option", (object)ScopedItemOptions.None); psCommandList.Add(psCommand1); string[] strArray = new string[4] { fullProfileFileName1, fullProfileFileName2, fullProfileFileName3, fullProfileFileName4 }; foreach (string str in strArray) { if (File.Exists(str)) { PSCommand psCommand2 = new PSCommand(); psCommand2.AddCommand(str, false); psCommandList.Add(psCommand2); } } return(psCommandList.ToArray()); }
/// <summary> /// Sets the list of breakpoints for the current debugging session. /// </summary> /// <param name="scriptFile">The ScriptFile in which breakpoints will be set.</param> /// <param name="lineNumbers">The line numbers at which breakpoints will be set.</param> /// <param name="clearExisting">If true, causes all existing breakpoints to be cleared before setting new ones.</param> /// <returns>An awaitable Task that will provide details about the breakpoints that were set.</returns> public async Task<BreakpointDetails[]> SetBreakpoints( ScriptFile scriptFile, int[] lineNumbers, bool clearExisting = true) { IEnumerable<Breakpoint> resultBreakpoints = null; if (clearExisting) { await this.ClearBreakpointsInFile(scriptFile); } if (lineNumbers.Length > 0) { // Fix for issue #123 - file paths that contain wildcard chars [ and ] need to // quoted and have those wildcard chars escaped. string escapedScriptPath = PowerShellContext.EscapeWildcardsInPath(scriptFile.FilePath); PSCommand psCommand = new PSCommand(); psCommand.AddCommand("Set-PSBreakpoint"); psCommand.AddParameter("Script", escapedScriptPath); psCommand.AddParameter("Line", lineNumbers.Length > 0 ? lineNumbers : null); resultBreakpoints = await this.powerShellContext.ExecuteCommand<Breakpoint>( psCommand); return resultBreakpoints .Select(BreakpointDetails.Create) .ToArray(); } return new BreakpointDetails[0]; }
/// <summary> /// Sets the list of breakpoints for the current debugging session. /// </summary> /// <param name="scriptFile">The ScriptFile in which breakpoints will be set.</param> /// <param name="lineNumbers">The line numbers at which breakpoints will be set.</param> /// <param name="clearExisting">If true, causes all existing breakpoints to be cleared before setting new ones.</param> /// <returns>An awaitable Task that will provide details about the breakpoints that were set.</returns> public async Task<BreakpointDetails[]> SetBreakpoints( ScriptFile scriptFile, int[] lineNumbers, bool clearExisting = true) { IEnumerable<Breakpoint> resultBreakpoints = null; if (clearExisting) { await this.ClearBreakpointsInFile(scriptFile); } if (lineNumbers.Length > 0) { PSCommand psCommand = new PSCommand(); psCommand.AddCommand("Set-PSBreakpoint"); psCommand.AddParameter("Script", scriptFile.FilePath); psCommand.AddParameter("Line", lineNumbers.Length > 0 ? lineNumbers : null); resultBreakpoints = await this.powerShellContext.ExecuteCommand<Breakpoint>( psCommand); return resultBreakpoints .Select(BreakpointDetails.Create) .ToArray(); } return new BreakpointDetails[0]; }
internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfile) { string str; string str2; string str3; string str4; PSObject obj2; List <PSCommand> list = new List <PSCommand>(); GetProfileObjectData(shellId, useTestProfile, out str, out str2, out str3, out str4, out obj2); PSCommand item = new PSCommand(); item.AddCommand("set-variable"); item.AddParameter("Name", "profile"); item.AddParameter("Value", obj2); item.AddParameter("Option", ScopedItemOptions.None); list.Add(item); string[] strArray = new string[] { str, str2, str3, str4 }; foreach (string str5 in strArray) { if (File.Exists(str5)) { item = new PSCommand(); item.AddCommand(str5, false); list.Add(item); } } return(list.ToArray()); }
public void disableMailbox(string login) { PowerShell powershell = PowerShell.Create(); powershell.Runspace = getRunspace(); PSCommand command = new PSCommand(); command.AddCommand("Disable-Mailbox"); command.AddParameter("Identity", login); command.AddParameter("Confirm", false); powershell.Commands = command; try { Collection<PSObject> commandResults = powershell.Invoke<PSObject>(); foreach (PSObject result in commandResults) { Console.WriteLine(result.ToString()); } //Form1.myForm.lblStatus.Text = powershell.Streams.Error.ToString(); } catch (Exception e) { Console.WriteLine(e.Message); } finally { powershell.Dispose(); } }
/// <summary> /// Gets an array of commands that can be run sequentially to set $profile and run the profile commands. /// </summary> /// <param name="shellId">The id identifying the host or shell used in profile file names.</param> /// <param name="useTestProfile">used from test not to overwrite the profile file names from development boxes</param> /// <returns></returns> internal static PSCommand[] GetProfileCommands(string shellId, bool useTestProfile) { List <PSCommand> commands = new List <PSCommand>(); string allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost; PSObject dollarProfile; HostUtilities.GetProfileObjectData(shellId, useTestProfile, out allUsersAllHosts, out allUsersCurrentHost, out currentUserAllHosts, out currentUserCurrentHost, out dollarProfile); PSCommand command = new PSCommand(); command.AddCommand("set-variable"); command.AddParameter("Name", "profile"); command.AddParameter("Value", dollarProfile); command.AddParameter("Option", ScopedItemOptions.None); commands.Add(command); string[] profilePaths = new string[] { allUsersAllHosts, allUsersCurrentHost, currentUserAllHosts, currentUserCurrentHost }; foreach (string profilePath in profilePaths) { if (!System.IO.File.Exists(profilePath)) { continue; } command = new PSCommand(); command.AddCommand(profilePath, false); commands.Add(command); } return(commands.ToArray()); }
/// <summary> /// Gets a specific users mailbox size /// </summary> /// <param name="userGuid"></param> /// <returns></returns> public StatMailboxSizes Get_MailboxSize(Guid userGuid, bool isArchive = false) { PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-MailboxStatistics"); cmd.AddParameter("Identity", userGuid.ToString()); cmd.AddParameter("DomainController", Config.ServiceSettings.PrimaryDC); if (isArchive) cmd.AddParameter("Archive"); _powershell.Commands = cmd; Collection<PSObject> psObjects = _powershell.Invoke(); if (psObjects.Count > 0) { StatMailboxSizes returnSize = new StatMailboxSizes(); foreach (PSObject obj in psObjects) { returnSize.UserGuid = userGuid; returnSize.MailboxDatabase = obj.Members["Database"].Value.ToString(); returnSize.TotalItemSize = obj.Members["TotalItemSize"].Value.ToString(); returnSize.TotalItemSizeInBytes = GetExchangeBytes(returnSize.TotalItemSize); returnSize.TotalDeletedItemSize = obj.Members["TotalDeletedItemSize"].Value.ToString(); returnSize.TotalDeletedItemSizeInBytes = GetExchangeBytes(returnSize.TotalDeletedItemSize); int itemCount = 0; int.TryParse(obj.Members["ItemCount"].Value.ToString(), out itemCount); returnSize.ItemCount = itemCount; int deletedItemCount = 0; int.TryParse(obj.Members["DeletedItemCount"].Value.ToString(), out deletedItemCount); returnSize.DeletedItemCount = deletedItemCount; returnSize.Retrieved = DateTime.Now; break; } return returnSize; } else { if (_powershell.Streams.Error.Count > 0) throw _powershell.Streams.Error[0].Exception; if (_powershell.Streams.Warning.Count > 0) throw new Exception(_powershell.Streams.Warning[0].Message); throw new Exception("No data was returned"); } }
public Guid Get_ExchangeGuid(string identity) { PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-Mailbox"); cmd.AddParameter("Identity", identity); cmd.AddParameter("DomainController", Config.ServiceSettings.PrimaryDC); _powershell.Commands = cmd; Collection<PSObject> psObjects = _powershell.Invoke(); if (_powershell.HadErrors) throw _powershell.Streams.Error[0].Exception; else { var foundUser = psObjects[0]; return Guid.Parse(foundUser.Properties["ExchangeGuid"].Value.ToString()); } }
public void Create(ExchMailbox mailbox) { if (string.IsNullOrEmpty(mailbox.Domain)) { throw new Exception("Mailbox domain not defined. [" + _log.Name + "]"); } ExchContext _context = ExchManager.Instance.Config.GetContext(mailbox.Domain); if(_context == null) { throw new Exception("Exchange context not defined for domain <" + mailbox.Domain + ">. [" + _log.Name + "]"); } mailbox.Context = _context; string _database = ExchManager.Instance.Config.GetDatabase(mailbox); if (string.IsNullOrEmpty(_database)) { throw new Exception("Mailbox database not defined. [" + _log.Name + "]"); } mailbox.Database = _database; PSCommand _command = new PSCommand(); _command.AddCommand("Enable-Mailbox"); _command.AddParameter("Identity", mailbox.Identity); _command.AddParameter("DomainController", mailbox.Context.Pdc); _command.AddParameter("Database", _database); Collection<PSObject> _result = ExchManager.Instance.InvokeCommand(_command, _context); foreach(PSObject _rec in _result) { if (_rec.Properties["PrimarySmtpAddress"] != null) { mailbox.Address = _rec.Properties["PrimarySmtpAddress"].Value.ToString(); } } }
public PSModuleInfo ImportPSSession(PSSession session, Action<PSDataStreams> psDataStreamAction) { if (session == null) { throw new ArgumentOutOfRangeException("session"); } var command = new PSCommand(); command.AddCommand(Constants.SessionScripts.ImportPSSession); command.AddParameter(Constants.ParameterNameStrings.Session, session); Collection<PSModuleInfo> modules; try { modules = this.runspace.ExecuteCommand<PSModuleInfo>(command, psDataStreamAction); if (modules.Count > 0) return modules[0]; } catch (Exception) { return null; } return null; }
public UsersObject GetUser(string identity, int exchangeVersion) { try { UsersObject user = new UsersObject(); // // // Get mailbox information // // // PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-Mailbox"); cmd.AddParameter("Identity", identity); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; Collection<PSObject> obj = powershell.Invoke(); if (obj != null && obj.Count > 0) { foreach (PSObject ps in obj) { this.logger.Debug("Pulling comment information for mailbox " + identity); if (ps.Members["Database"].Value != null) user.CurrentMailboxDatabase = ps.Members["Database"].Value.ToString(); if (ps.Members["DeliverToMailboxAndForward"].Value != null) user.DeliverToMailboxAndForward = bool.Parse(ps.Members["DeliverToMailboxAndForward"].Value.ToString()); if (ps.Members["LitigationHoldEnabled"].Value != null) user.LitigationHoldEnabled = bool.Parse(ps.Members["LitigationHoldEnabled"].Value.ToString()); if (ps.Members["LitigationHoldDuration"].Value != null) { string value = ps.Members["LitigationHoldDuration"].Value.ToString(); if (!value.Equals("Unlimited", StringComparison.CurrentCultureIgnoreCase)) { TimeSpan span = TimeSpan.Parse(value); user.LitigationHoldDuration = span.Days; } } if (ps.Members["HiddenFromAddressListsEnabled"].Value != null) user.MailboxHiddenFromGAL = bool.Parse(ps.Members["HiddenFromAddressListsEnabled"].Value.ToString()); if (ps.Members["RetentionComment"].Value != null) user.LitigationHoldComment = ps.Members["RetentionComment"].Value.ToString(); if (ps.Members["RetentionUrl"].Value != null) user.LitigationHoldUrl = ps.Members["RetentionUrl"].Value.ToString(); if (ps.Members["ForwardingAddress"].Value != null) user.ForwardingTo = ps.Members["ForwardingAddress"].Value.ToString(); if (ps.Members["SamAccountName"].Value != null) user.sAMAccountName = ps.Members["SamAccountName"].Value.ToString(); if (ps.Members["UserPrincipalName"].Value != null) user.UserPrincipalName = ps.Members["UserPrincipalName"].Value.ToString(); if (ps.Members["ThrottlingPolicy"].Value != null) user.ThrottlingPolicy = ps.Members["ThrottlingPolicy"].Value.ToString(); if (ps.Members["Alias"].Value != null) user.ExchangeAlias = ps.Members["Alias"].Value.ToString(); if (ps.Members["PrimarySmtpAddress"].Value != null) user.PrimarySmtpAddress = ps.Members["PrimarySmtpAddress"].Value.ToString(); if (ps.Members["DistinguishedName"].Value != null) user.DistinguishedName = ps.Members["DistinguishedName"].Value.ToString(); if (ps.Members["ArchiveDatabase"].Value != null) user.ArchiveDatabase = ps.Members["ArchiveDatabase"].Value.ToString(); if (ps.Members["ArchiveName"].Value != null) user.ArchiveName = ps.Members["ArchiveName"].Value.ToString(); if (exchangeVersion == 2013) user.HasExchangePicture = bool.Parse(ps.Members["HasPicture"].Value.ToString()); // Get email aliases this.logger.Debug("Pulling email aliases for " + identity); user.EmailAliases = new List<string>(); if (ps.Members["EmailAddresses"].Value != null) { PSObject multiValue = (PSObject)ps.Members["EmailAddresses"].Value; ArrayList addresses = (ArrayList)multiValue.BaseObject; // Convert to string array string[] stringEmailAddresses = (string[])addresses.ToArray(typeof(string)); foreach (string s in stringEmailAddresses) { if (!s.StartsWith("SMTP:")) { user.EmailAliases.Add(s.Replace("smtp:", string.Empty)); } } } } } if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; // // // Get full access permissions // // // this.logger.Debug("Getting full access permissions for " + identity); user.FullAccessUsers = new List<string>(); cmd = new PSCommand(); cmd.AddCommand("Get-MailboxPermission"); cmd.AddParameter("Identity", identity); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; obj = powershell.Invoke(); if (obj != null && obj.Count > 0) { foreach (PSObject ps in obj) { // Only get users with a \ in them. Otherwise they are not users if (ps.Members["User"].Value.ToString().Contains("\\")) { this.logger.Debug("Found a user that has a permission to mailbox " + identity + "... now checking if it is deny permission or allow permission"); // We don't care about the deny permissions if (!bool.Parse(ps.Members["Deny"].Value.ToString())) { this.logger.Debug("Found a user that has a permission to mailbox " + identity + ": " + ps.Members["User"].Value.ToString()); // Get the permissions that this user has PSObject multiValue = (PSObject)ps.Members["AccessRights"].Value; ArrayList accessRights = (ArrayList)multiValue.BaseObject; // Convert to string array string[] stringAccessRights = (string[])accessRights.ToArray(typeof(string)); // Fix the sAMAccountName by removing the domain name string sAMAccountName = ps.Members["User"].Value.ToString().Split('\\')[1]; // Check if it is full access or send as if (stringAccessRights.Contains("FullAccess")) user.FullAccessUsers.Add(sAMAccountName); } } } } if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; // // // Get send-as permissions // // // this.logger.Debug("Getting send-as permissions for " + identity); user.SendAsUsers = new List<string>(); cmd = new PSCommand(); cmd.AddCommand("Get-ADPermission"); cmd.AddParameter("Identity", identity); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; obj = powershell.Invoke(); if (obj != null && obj.Count > 0) { foreach (PSObject ps in obj) { if (ps.Members["ExtendedRights"].Value != null) { // Only get users with a \ in them. Otherwise they are not users if (ps.Members["User"].Value.ToString().Contains("\\")) { this.logger.Debug("Found a user that has an extended rights permission to mailbox " + identity + "... now checking if it is deny permission or allow permission"); // We don't care about the deny permissions if (!bool.Parse(ps.Members["Deny"].Value.ToString())) { this.logger.Debug("Found a user that has an extended rights permission to mailbox " + identity + ": " + ps.Members["User"].Value.ToString()); // Get the permissions that this user has PSObject multiValue = (PSObject)ps.Members["ExtendedRights"].Value; ArrayList accessRights = (ArrayList)multiValue.BaseObject; // Convert to string array string[] stringAccessRights = (string[])accessRights.ToArray(typeof(string)); // Fix the sAMAccountName by removing the domain name string sAMAccountName = ps.Members["User"].Value.ToString().Split('\\')[1]; // Check if it is full access or send as if (stringAccessRights.Contains("Send-As")) user.SendAsUsers.Add(sAMAccountName); } } } } } if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; // // // Get send-as permissions // // // this.logger.Debug("Getting send on behalf permissions for " + identity); user.SendOnBehalf = new List<string>(); return user; } catch (Exception ex) { this.logger.Error("Failed to get mailbox information for " + identity, ex); throw; } }
public void DeleteAllMailboxes(string companyCode) { try { this.logger.Info("Disabling all mailboxes for " + companyCode); PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-Mailbox"); cmd.AddParameter("Filter", string.Format("CustomAttribute1 -eq '{0}'", companyCode)); cmd.AddParameter("DomainController", domainController); cmd.AddCommand("Disable-Mailbox"); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed to disable all mailboxes for company " + companyCode, ex); throw; } }
/// <summary> /// Pre-processor for debugger commands. /// Parses special debugger commands and converts to equivalent script for remote execution as needed. /// </summary> /// <param name="commands">PSCommand</param> /// <param name="isDebuggerActive">True if debugger is active.</param> /// <param name="isDebuggerRemote">True if active debugger is pushed and is a remote debugger.</param> /// <param name="commandArgument">Command argument.</param> /// <returns>PreProcessCommandResult type if preprocessing occurred.</returns> private static PreProcessCommandResult PreProcessDebuggerCommand( PSCommand commands, bool isDebuggerActive, bool isDebuggerRemote, out DebuggerCommandArgument commandArgument) { commandArgument = new DebuggerCommandArgument(); PreProcessCommandResult result = PreProcessCommandResult.None; if ((commands.Commands.Count == 0) || (commands.Commands[0].IsScript)) { return result; } var command = commands.Commands[0]; string commandText = command.CommandText; if (commandText.Equals(DebuggerUtils.GetDebuggerStopArgsFunctionName, StringComparison.OrdinalIgnoreCase)) { // // __Get-PSDebuggerStopArgs private virtual command. // No input parameters. // Returns DebuggerStopEventArgs object. // // Evaluate this command only if the debugger is activated. if (!isDebuggerActive) { return PreProcessCommandResult.ValidNotProcessed; } // Translate into debugger method call. ScriptBlock scriptBlock = ScriptBlock.Create("$host.Runspace.Debugger.GetDebuggerStopArgs()"); scriptBlock.LanguageMode = PSLanguageMode.FullLanguage; commands.Clear(); commands.AddCommand("Invoke-Command").AddParameter("ScriptBlock", scriptBlock).AddParameter("NoNewScope", true); result = PreProcessCommandResult.GetDebuggerStopArgs; } else if (commandText.Equals(DebuggerUtils.SetDebuggerActionFunctionName, StringComparison.OrdinalIgnoreCase)) { // // __Set-PSDebuggerAction private virtual command. // DebuggerResumeAction enum input parameter. // Returns void. // // Evaluate this command only if the debugger is activated. if (!isDebuggerActive) { return PreProcessCommandResult.ValidNotProcessed; } if ((command.Parameters == null) || (command.Parameters.Count == 0) || (!command.Parameters[0].Name.Equals("ResumeAction", StringComparison.OrdinalIgnoreCase))) { throw new PSArgumentException("ResumeAction"); } DebuggerResumeAction? resumeAction = null; PSObject resumeObject = command.Parameters[0].Value as PSObject; if (resumeObject != null) { try { resumeAction = (DebuggerResumeAction)resumeObject.BaseObject; } catch (InvalidCastException) { } } if (resumeAction == null) { throw new PSArgumentException("ResumeAction"); } commandArgument.ResumeAction = resumeAction; result = PreProcessCommandResult.SetDebuggerAction; } else if (commandText.Equals(DebuggerUtils.SetDebugModeFunctionName, StringComparison.OrdinalIgnoreCase)) { // // __Set-PSDebugMode private virtual command. // DebugModes enum input parameter. // Returns void. // if ((command.Parameters == null) || (command.Parameters.Count == 0) || (!command.Parameters[0].Name.Equals("Mode", StringComparison.OrdinalIgnoreCase))) { throw new PSArgumentException("Mode"); } DebugModes? mode = null; PSObject modeObject = command.Parameters[0].Value as PSObject; if (modeObject != null) { try { mode = (DebugModes)modeObject.BaseObject; } catch (InvalidCastException) { } } if (mode == null) { throw new PSArgumentException("Mode"); } commandArgument.Mode = mode; result = PreProcessCommandResult.SetDebugMode; } else if (commandText.Equals(DebuggerUtils.SetDebuggerStepMode, StringComparison.OrdinalIgnoreCase)) { // // __Set-PSDebuggerStepMode private virtual command. // Boolean Enabled input parameter. // Returns void. // if ((command.Parameters == null) || (command.Parameters.Count == 0) || (!command.Parameters[0].Name.Equals("Enabled", StringComparison.OrdinalIgnoreCase))) { throw new PSArgumentException("Enabled"); } bool enabled = (bool)command.Parameters[0].Value; commandArgument.DebuggerStepEnabled = enabled; result = PreProcessCommandResult.SetDebuggerStepMode; } else if (commandText.Equals(DebuggerUtils.SetPSUnhandledBreakpointMode, StringComparison.OrdinalIgnoreCase)) { // // __Set-PSUnhandledBreakpointMode private virtual command. // UnhandledBreakpointMode input parameter. // Returns void. // if ((command.Parameters == null) || (command.Parameters.Count == 0) || (!command.Parameters[0].Name.Equals("UnhandledBreakpointMode", StringComparison.OrdinalIgnoreCase))) { throw new PSArgumentException("UnhandledBreakpointMode"); } UnhandledBreakpointProcessingMode? mode = null; PSObject modeObject = command.Parameters[0].Value as PSObject; if (modeObject != null) { try { mode = (UnhandledBreakpointProcessingMode)modeObject.BaseObject; } catch (InvalidCastException) { } } if (mode == null) { throw new PSArgumentException("Mode"); } commandArgument.UnhandledBreakpointMode = mode; result = PreProcessCommandResult.SetPreserveUnhandledBreakpointMode; } return result; }
public void NewMailbox(UsersObject user) { try { this.logger.Debug("Creating new mailbox for "+ user.UserPrincipalName); PSCommand cmd = new PSCommand(); cmd.AddCommand("Enable-Mailbox"); cmd.AddParameter("Identity", user.UserPrincipalName); cmd.AddParameter("PrimarySmtpAddress", user.PrimarySmtpAddress); cmd.AddParameter("AddressBookPolicy", user.CompanyCode + " ABP"); this.logger.Debug("Checking activesync policy for " + user.UserPrincipalName); if (!string.IsNullOrEmpty(user.ActiveSyncName)) cmd.AddParameter("ActiveSyncMailboxPolicy", user.ActiveSyncName); this.logger.Debug("Checking if we are putting this new mailbox in a specific database " + user.UserPrincipalName); if (!string.IsNullOrEmpty(user.CurrentMailboxDatabase)) cmd.AddParameter("Database", user.CurrentMailboxDatabase); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; this.logger.Debug("Invoking powershell to create new mailbox for " + user.UserPrincipalName); powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed to create new mailbox for " + user.UserPrincipalName, ex); throw; } }
public void DeleteDistributionGroup(string identity) { try { PSCommand cmd = new PSCommand(); cmd.AddCommand("Remove-DistributionGroup"); cmd.AddParameter("Identity", identity); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; powershell.Invoke(); if (powershell.HadErrors) { ErrorCategory errCategory = powershell.Streams.Error[0].CategoryInfo.Category; string reason = powershell.Streams.Error[0].CategoryInfo.Reason; if (errCategory != ErrorCategory.NotSpecified && !reason.Equals("ManagementObjectNotFoundException")) throw powershell.Streams.Error[0].Exception; else this.logger.Info("Failed to remove distribution group " + identity + " because it didn't exist"); } } catch (Exception ex) { this.logger.Error("Failed to delete distribution group " + identity, ex); throw; } }
public void NewGlobalAddressList(string name, string recipientFilter) { try { PSCommand cmd = new PSCommand(); cmd.AddCommand("New-GlobalAddressList"); cmd.AddParameter("Name", name); cmd.AddParameter("RecipientFilter", recipientFilter); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed to create new global address list named " + name + " with filter " + recipientFilter, ex); throw; } }
public void NewLitigationHold(string userPrincipalName, string comment, string url, int? days) { try { this.logger.Debug("Enabling litigation hold for " + userPrincipalName); PSCommand cmd = new PSCommand(); cmd.AddCommand("Set-Mailbox"); cmd.AddParameter("Identity", userPrincipalName); cmd.AddParameter("LitigationHoldEnabled", true); if (!string.IsNullOrEmpty(comment)) cmd.AddParameter("RetentionComment", comment); else cmd.AddParameter("RetentionComment", null); if (!string.IsNullOrEmpty(url)) cmd.AddParameter("RetentionUrl", url); else cmd.AddParameter("RetentionUrl", null); if (days != null) cmd.AddParameter("LitigationHoldDuration", days); else cmd.AddParameter("LitigationHoldDuration", null); cmd.AddParameter("Confirm", false); cmd.AddParameter("Force"); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; Collection<PSObject> obj = powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed to enable litigation hold for " + userPrincipalName, ex); throw; } }
/// <summary> /// Gets a list of mailbox sizes Exchange /// </summary> /// <returns></returns> public List<MailboxUser> Get_MailboxSizes() { PowerShell powershell = null; try { // DEBUG logger.Debug("Retrieving a list of mailbox users from the SQL database..."); // Start clock Stopwatch stopwatch = Stopwatch.StartNew(); // Get a list of users from the database List<ADUser> allUsers = DbSql.Get_Users(); // Our return object of information List<MailboxUser> users = new List<MailboxUser>(); // Now loop through the databases and query the information foreach (ADUser user in allUsers) { if (user.MailboxPlanID > 0) { // DEBUG logger.Debug("Retrieving mailbox statistics for user " + user); // Our MailboxUser object to store this users information MailboxUser currentUser = new MailboxUser(); try { // Run commands powershell = PowerShell.Create(); powershell.Runspace = runspace; // Get Databases PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-MailboxStatistics"); cmd.AddParameter("Identity", user.UserPrincipalName); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; // Now read the returned values Collection<PSObject> foundStatistics = powershell.Invoke(); foreach (PSObject o in foundStatistics) { currentUser.UserPrincipalName = user.UserPrincipalName; currentUser.ItemCount = int.Parse(o.Members["ItemCount"].Value.ToString(), CultureInfo.InvariantCulture); currentUser.DeletedItemCount = int.Parse(o.Members["DeletedItemCount"].Value.ToString(), CultureInfo.InvariantCulture); currentUser.TotalItemSize = o.Members["TotalItemSize"].Value.ToString(); currentUser.TotalDeletedItemSize = o.Members["TotalDeletedItemSize"].Value.ToString(); currentUser.Database = o.Members["Database"].Value.ToString(); currentUser.MailboxDataRetrieved = DateTime.Now; } // Log the powershell commands LogPowershellCommands(ref powershell); // Find all the errors if (powershell.HadErrors) { // Log all errors detected foreach (ErrorRecord err in powershell.Streams.Error) { logger.Error("Error getting mailbox size for " + user, err.Exception); // Compile message StringBuilder sb = new StringBuilder(); sb.AppendLine("Failed to get mailbox size for: " + user); sb.AppendLine(""); sb.AppendLine("Recommended Action:"); sb.AppendLine("This could be because the user no longer exists in Active Directory but still exists in the database."); sb.AppendLine("If that is the case simply delete the user from CloudPanel. If the issues stays the same please contact support."); sb.AppendLine(""); sb.AppendLine("Error:"); sb.AppendLine(err.Exception.ToString()); // Send message Support.SendEmailMessage("Failed to get mailbox size for: " + user, sb.ToString()); } // Log all warnings detected foreach (WarningRecord err in powershell.Streams.Warning) { logger.Error("Warning getting mailbox size for " + user + ": " + err.Message); } } else { logger.Info("Successfully retrieved mailbox size information for " + currentUser.UserPrincipalName); users.Add(currentUser); } } catch (Exception ex) { logger.Fatal("Failed to retrieve mailbox size for " + user, ex); } } } // Stop the clock stopwatch.Stop(); // Log the success logger.Info("Successfully retrieved a complete list of mailbox sizes from Exchange."); // Return values return users; } catch (Exception ex) { throw; } finally { if (powershell != null) powershell.Dispose(); } }
public void DeleteLitigationHold(string userPrincipalName) { try { this.logger.Debug("Disabling litigation hold for " + userPrincipalName); PSCommand cmd = new PSCommand(); cmd.AddCommand("Set-Mailbox"); cmd.AddParameter("Identity", userPrincipalName); cmd.AddParameter("LitigationHoldEnabled", false); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed to disable litigation hold for" + userPrincipalName, ex); throw; } }
/// <summary> /// Gets the calendar name because it can be in a different language /// </summary> /// <param name="userPrincipalName"></param> /// <returns></returns> public string Get_CalendarName(string userPrincipalName) { PowerShell powershell = null; try { // DEBUG // logger.Debug("Getting calendar name for " + userPrincipalName); // Run commands powershell = PowerShell.Create(); powershell.Runspace = runspace; // // First we need to remove the default calendar permissions and add the security group // PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-MailboxFolderStatistics"); cmd.AddParameter("Identity", userPrincipalName); cmd.AddParameter("FolderScope", "Calendar"); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; // Default calendar name in English string calendarName = "Calendar"; Collection<PSObject> obj = powershell.Invoke(); if (obj != null && obj.Count > 0) { foreach (PSObject ps in obj) { if (ps.Members["FolderType"] != null) { string folderType = ps.Members["FolderType"].Value.ToString(); if (folderType.Equals("Calendar")) { calendarName = ps.Members["Name"].Value.ToString(); break; } } } } return calendarName; } catch (Exception ex) { logger.Error("Error getting calendar name for " + userPrincipalName, ex); // Return the default name return "Calendar"; } finally { if (powershell != null) powershell.Dispose(); } }
private async Task HandleExpandAliasRequest( string content, RequestContext<string> requestContext) { var script = @" function __Expand-Alias { param($targetScript) [ref]$errors=$null $tokens = [System.Management.Automation.PsParser]::Tokenize($targetScript, $errors).Where({$_.type -eq 'command'}) | Sort Start -Descending foreach ($token in $tokens) { $definition=(Get-Command ('`'+$token.Content) -CommandType Alias -ErrorAction SilentlyContinue).Definition if($definition) { $lhs=$targetScript.Substring(0, $token.Start) $rhs=$targetScript.Substring($token.Start + $token.Length) $targetScript=$lhs + $definition + $rhs } } $targetScript }"; var psCommand = new PSCommand(); psCommand.AddScript(script); await this.editorSession.PowerShellContext.ExecuteCommand<PSObject>(psCommand); psCommand = new PSCommand(); psCommand.AddCommand("__Expand-Alias").AddArgument(content); var result = await this.editorSession.PowerShellContext.ExecuteCommand<string>(psCommand); await requestContext.SendResult(result.First().ToString()); }
private PSCommand CreatePsCommandNotOverriden(string line, bool isScript, bool? useNewScope) { PSCommand command = new PSCommand(); if (isScript) { if (useNewScope.HasValue) { command.AddScript(line, useNewScope.Value); return command; } command.AddScript(line); return command; } if (useNewScope.HasValue) { command.AddCommand(line, useNewScope.Value); return command; } command.AddCommand(line); return command; }
public void DeleteOfflineAddressBook(string name) { try { this.logger.Info("Deleting offline address book " + name); PSCommand cmd = new PSCommand(); cmd.AddCommand("Remove-OfflineAddressBook"); cmd.AddParameter("Identity", name); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; powershell.Invoke(); if (powershell.HadErrors) { ErrorCategory errCategory = powershell.Streams.Error[0].CategoryInfo.Category; string reason = powershell.Streams.Error[0].CategoryInfo.Reason; if (errCategory != ErrorCategory.NotSpecified && !reason.Equals("ManagementObjectNotFoundException")) throw powershell.Streams.Error[0].Exception; else this.logger.Info("Failed to delete offline address book " + name + " but it could not be found. Must have already been deleted."); } } catch (Exception ex) { this.logger.Error("Failed to delete offline address book " + name, ex); throw; } }
public void DeleteMailbox(string userPrincipalName) { try { PSCommand cmd = new PSCommand(); cmd.AddCommand("Disable-Mailbox"); cmd.AddParameter("Identity", userPrincipalName); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; powershell.Invoke(); if (powershell.HadErrors) { ErrorCategory errCategory = powershell.Streams.Error[0].CategoryInfo.Category; string reason = powershell.Streams.Error[0].CategoryInfo.Reason; if (errCategory != ErrorCategory.NotSpecified && !reason.Equals("ManagementObjectNotFoundException")) throw powershell.Streams.Error[0].Exception; else this.logger.Info("Attempted to disable mailbox " + userPrincipalName + " but it could not be found. Must have already been disabled."); } } catch (Exception ex) { this.logger.Error("Failed to disable mailbox " + userPrincipalName, ex); throw; } }
protected async Task HandleShowOnlineHelpRequest( string helpParams, RequestContext<object> requestContext) { if (helpParams == null) { helpParams = "get-help"; } var psCommand = new PSCommand(); psCommand.AddCommand("Get-Help"); psCommand.AddArgument(helpParams); psCommand.AddParameter("Online"); await editorSession.PowerShellContext.ExecuteCommand<object>( psCommand); await requestContext.SendResult(null); }
public void NewAddressBookPolicy(string name, string gal, string oab, string room, string[] addressLists) { try { PSCommand cmd = new PSCommand(); cmd.AddCommand("New-AddressBookPolicy"); cmd.AddParameter("Name", name); cmd.AddParameter("AddressLists", addressLists); cmd.AddParameter("GlobalAddressList", gal); cmd.AddParameter("OfflineAddressBook", oab); cmd.AddParameter("RoomList", room); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error(string.Format("Failed to create new address book policy named {0} with GAL {1}, OAB {2}, room list {3} and the following address lists: {4}", name, gal, oab, room, String.Join(",", addressLists)), ex); throw; } }
private async Task<CommandInfo> GetCommandInfo(string commandName) { PSCommand command = new PSCommand(); command.AddCommand("Get-Command"); command.AddArgument(commandName); var results = await this.powerShellContext.ExecuteCommand<CommandInfo>(command); return results.FirstOrDefault(); }
public void NewArchiveMailbox(UsersObject user) { try { this.logger.Debug("Creating new archive mailbox for " + user.UserPrincipalName); if (user.ArchivingEnabled && user.ArchivePlan > 0) { PSCommand cmd = new PSCommand(); cmd.AddCommand("Enable-Mailbox"); cmd.AddParameter("Identity", user.UserPrincipalName); cmd.AddParameter("Archive"); if (!string.IsNullOrEmpty(user.ArchiveDatabase)) cmd.AddParameter("ArchiveDatabase", user.ArchiveDatabase); if (!string.IsNullOrEmpty(user.ArchiveName)) cmd.AddParameter("ArchiveName", user.ArchiveName); cmd.AddParameter("Confirm", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; Collection<PSObject> obj = powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } else this.logger.Debug("Unable to create archive mailbox because the plan was not set for " + user.UserPrincipalName); } catch (Exception ex) { this.logger.Error("Failed to create new archive mailbox for " + user.UserPrincipalName, ex); throw; } }
/// <summary> /// Gets a list of Exchange database names /// </summary> /// <returns></returns> public List<MailboxDatabase> Get_ExchangeDatabases() { PowerShell powershell = null; try { // DEBUG logger.Debug("Retrieving a list of Exchange databases..."); // Start clock Stopwatch stopwatch = Stopwatch.StartNew(); // Run commands powershell = PowerShell.Create(); powershell.Runspace = runspace; // Get Databases PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-MailboxDatabase"); cmd.AddParameter("Status"); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; // Store what we find in this list so we can return the names of the databases List<MailboxDatabase> databases = new List<MailboxDatabase>(); // When retrieved DateTime when = DateTime.Now; // Now read the returned values Collection<PSObject> foundDatabases = powershell.Invoke(); if (foundDatabases != null) { foreach (PSObject o in foundDatabases) { MailboxDatabase db = new MailboxDatabase(); db.Identity = o.Members["Identity"].Value.ToString(); // DEBUG logger.Debug("Found database " + db.Identity); db.LogFolderPath = o.Members["LogFolderPath"].Value.ToString(); db.EDBFilePath = o.Members["EdbFilePath"].Value.ToString(); db.IsMailboxDatabase = bool.Parse(o.Members["IsMailboxDatabase"].Value.ToString()); db.IsPublicFolderDatabase = bool.Parse(o.Members["IsPublicFolderDatabase"].Value.ToString()); if (o.Members["Server"].Value != null) db.Server = o.Members["Server"].Value.ToString(); if (o.Members["DatabaseSize"].Value != null) { db.DatabaseSize = o.Members["DatabaseSize"].Value.ToString(); // DEBUG logger.Debug("Size of the database is " + o.Members["DatabaseSize"].Value.ToString()); logger.Debug("Size of the database after formatted is " + db.DatabaseSize.ToString()); } db.WhenRetrieved = when; databases.Add(db); } } // Log the powershell commands LogPowershellCommands(ref powershell); // Find all the error if (powershell.HadErrors) { // Log all errors detected foreach (ErrorRecord err in powershell.Streams.Error) { string exception = err.Exception.ToString(); // Log the exception logger.Fatal("Error retrieving mailbox database sizes: " + exception); throw err.Exception; } } // Stop the clock stopwatch.Stop(); // Log the success logger.Info("Successfully retrieved a list of databases from Exchange."); // Return values return databases; } catch (Exception ex) { throw; } finally { if (powershell != null) powershell.Dispose(); } }
public string NewContact(string displayName, string email, bool isHidden, string companyCode, string organizationalUnit) { try { this.logger.Debug("Creating new Exchange contact named " + displayName + " with email address " + email); PSCommand cmd = new PSCommand(); cmd.AddCommand("New-MailContact"); //cmd.AddParameter("Alias", email); cmd.AddParameter("Name", displayName); cmd.AddParameter("PrimarySmtpAddress", string.Format("{0}@{1}", Guid.NewGuid(), email.Split('@')[1])); cmd.AddParameter("ExternalEmailAddress", email); cmd.AddParameter("OrganizationalUnit", organizationalUnit); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; Collection<PSObject> obj = powershell.Invoke(); if (!powershell.HadErrors) { // Get the distinguished name string distinguishedName = ""; foreach (PSObject o in obj) { if (o.Properties["DistinguishedName"] != null) distinguishedName = o.Properties["DistinguishedName"].Value.ToString(); } cmd = new PSCommand(); cmd.AddCommand("Set-MailContact"); cmd.AddParameter("Identity", distinguishedName); cmd.AddParameter("CustomAttribute1", companyCode); cmd.AddParameter("HiddenFromAddressListsEnabled", isHidden); cmd.AddParameter("EmailAddressPolicyEnabled", false); cmd.AddParameter("DomainController", domainController); powershell.Commands = cmd; powershell.Invoke(); return distinguishedName; } else throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed to create new Exchange contact " + displayName, ex); throw; } }
/// <summary> /// Sets the mailbox default calendar permissions by removing the default and adding their company's ExchangeSecurity group to the AvailabilityOnly /// </summary> /// <param name="userPrincipalName"></param> /// <param name="companyCode"></param> public void Set_MailboxCalendarPermission(string userPrincipalName, string companyCode) { PowerShell powershell = null; try { // Strip whitespace from company code companyCode = companyCode.Replace(" ", string.Empty); // DEBUG logger.Debug("Removing default permissions for mailbox calendar and adding correct permissions for user " + userPrincipalName); // Start clock Stopwatch stopwatch = Stopwatch.StartNew(); // Run commands powershell = PowerShell.Create(); powershell.Runspace = runspace; // Enable the mailbox PSCommand cmd = new PSCommand(); // Get the calendar name string calendarName = Get_CalendarName(userPrincipalName); // Remove default calendar permissions cmd.AddCommand("Set-MailboxFolderPermission"); cmd.AddParameter("Identity", string.Format(@"{0}:\{1}", userPrincipalName, calendarName)); cmd.AddParameter("User", "Default"); cmd.AddParameter("AccessRights", "None"); cmd.AddParameter("DomainController", this.domainController); // Add calendar permissions for the group cmd.AddStatement(); cmd.AddCommand("Add-MailboxFolderPermission"); cmd.AddParameter("Identity", string.Format(@"{0}:\{1}", userPrincipalName, calendarName)); cmd.AddParameter("User", "ExchangeSecurity@" + companyCode); cmd.AddParameter("AccessRights", "AvailabilityOnly"); cmd.AddParameter("DomainController", this.domainController); powershell.Commands = cmd; powershell.Invoke(); // Log the powershell commands LogPowershellCommands(ref powershell); // Find all the error if (powershell.HadErrors) { // Log all warning detected foreach (WarningRecord warn in powershell.Streams.Warning) { string warnMessage = warn.Message; if (!warnMessage.Contains("completed successfully but no permissions")) logger.Warn("Warning was generated running the command to modify the mailbox permissions for " + userPrincipalName + ": " + warnMessage); } // Log all errors detected foreach (ErrorRecord err in powershell.Streams.Error) { string exception = err.Exception.ToString(); if (exception.Contains("An existing permission entry was found for user")) logger.Info("Attempted to modify permission on " + userPrincipalName + " but the permission already existed."); else throw err.Exception; } } // Stop the clock stopwatch.Stop(); // Log the success logger.Info("Successfully modified calendar permissions for " + userPrincipalName); } catch (Exception ex) { throw; } finally { if (powershell != null) powershell.Dispose(); } }
public void NewDomain(string domainName, DomainType domainType) { try { PSCommand cmd = new PSCommand(); cmd.AddCommand("New-AcceptedDomain"); cmd.AddParameter("Name", domainName); cmd.AddParameter("DomainName", domainName); cmd.AddParameter("DomainController", domainController); switch (domainType) { case DomainType.InternalRelayDomain: cmd.AddParameter("DomainType", "InternalRelay"); break; case DomainType.ExternalRelayDomain: cmd.AddParameter("DomainType", "ExternalRelay"); break; default: cmd.AddParameter("DomainType", "Authoritative"); break; } powershell.Commands = cmd; powershell.Invoke(); if (powershell.HadErrors) throw powershell.Streams.Error[0].Exception; } catch (Exception ex) { this.logger.Error("Failed enable new accepted domain " + domainName, ex); throw; } }