Beispiel #1
1
        public void InvokeCommands(PSCommand[] profileCommands)
        {
            WithLock(() =>
            {
                using (var powerShell = System.Management.Automation.PowerShell.Create())
                {
                    powerShell.Runspace = _runspace;

                    foreach (PSCommand command in profileCommands)
                    {
                        powerShell.Commands = command;
                        powerShell.AddCommand("out-default");
                        powerShell.Invoke();
                    }
                }
            });
        }
        /// <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];
        }
        public PSSession Create(string userName, SecureString password, string connectionUri, string schemauri, Action<PSDataStreams> psDataStreamAction)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentOutOfRangeException("userName");
            }

            if (password == null)
            {
                throw new ArgumentOutOfRangeException("password");
            }

            if (string.IsNullOrEmpty(connectionUri))
            {
                throw new ArgumentOutOfRangeException("connectionUri");
            }
            this.runspace.SetCredentialVariable(userName, password);
            var command = new PSCommand();
            string importpssessionscript = Constants.SessionScripts.NewPSSessionScriptWithBasicAuth;
            if (AllowRedirection) importpssessionscript += Constants.SessionScripts.AllowRedirectionInNewPSSession;
            command.AddScript(string.Format(importpssessionscript, schemauri, connectionUri));
            Collection<PSSession> sessions = this.runspace.ExecuteCommand<PSSession>(command, psDataStreamAction);
            if (sessions.Count > 0) this.runspace.SetRunspaceVariable(Constants.ParameterNameStrings.Session, sessions[0]);
            return sessions.Count == 0 ? null : sessions[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)
            {
                // 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];
        }
Beispiel #5
0
 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();
     }
 }
Beispiel #6
0
        public void assignPhoto(string login, string fileLocation)
        {
            using (var context = new PrincipalContext(ContextType.Domain, Form1._Domain, Form1._AdminUser, Form1._Password))
            {
                //Import-RecipientDataProperty -Identity "Scott Carter" -Picture -FileData ([Byte[]]$(Get-Content -Path "C:\StaffPhotos\DJScott1.jpg" -Encoding Byte -ReadCount 0))
                PowerShell powershell = PowerShell.Create();
                powershell.Runspace = getRunspace();
                PSCommand command = new PSCommand();

                command.AddScript("Import-RecipientDataProperty -Identity " + '\u0022' + myAD.GetAccountName(login) + '\u0022' + " -Picture -FileData ([Byte[]]$(Get-Content -Path " + '\u0022' + fileLocation + '\u0022' + " -Encoding Byte -ReadCount 0))");
                powershell.Commands = command;
                try
                {
                    Collection<PSObject> commandResults = powershell.Invoke<PSObject>();
                    foreach (PSObject result in commandResults)
                    {
                        Form1.myForm.lblExchMessage.Text = result.ToString();
                        Form1.myForm.lblExchMessage.Visible = true;
                    }
                }
                catch (Exception e)
                {
                    Form1.myForm.lblExchMessage.Text = e.Message;
                    Form1.myForm.lblExchMessage.Visible = true;
                }
                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 = 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();
        }
Beispiel #8
0
    public static string ToDebuggerString(SMA.PSCommand command)
    {
        if (command.Commands.Count == 0)
        {
            return("{}");
        }

        return($"{{{command.Commands[0].CommandText}}}");
    }
Beispiel #9
0
 internal PSCommand(PSCommand commandToClone)
 {
     this.commands = new CommandCollection();
     foreach (Command command in commandToClone.Commands)
     {
         Command item = command.Clone();
         this.commands.Add(item);
         this.currentCommand = item;
     }
 }
Beispiel #10
0
        private async void OnLanguageServiceClientConnectAsync(
            object sender,
            ChannelBase serverChannel)
        {
            MessageDispatcher messageDispatcher = new MessageDispatcher(this.logger);

            ProtocolEndpoint protocolEndpoint =
                new ProtocolEndpoint(
                    serverChannel,
                    messageDispatcher,
                    this.logger);

            protocolEndpoint.UnhandledException += ProtocolEndpoint_UnhandledException;

            this.editorSession =
                CreateSession(
                    this.hostDetails,
                    this.profilePaths,
                    protocolEndpoint,
                    messageDispatcher,
                    this.enableConsoleRepl);

            this.languageServer =
                new LanguageServer(
                    this.editorSession,
                    messageDispatcher,
                    protocolEndpoint,
                    this.serverCompletedTask,
                    this.logger);

            await this.editorSession.PowerShellContext.ImportCommandsModuleAsync(
                Path.Combine(
                    Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location),
                    @"..\Commands"));

            this.languageServer.Start();

            // TODO: This can be moved to the point after the $psEditor object
            // gets initialized when that is done earlier than LanguageServer.Initialize
            foreach (string module in this.additionalModules)
            {
                var command =
                    new System.Management.Automation.PSCommand()
                    .AddCommand("Microsoft.PowerShell.Core\\Import-Module")
                    .AddParameter("Name", module);

                await this.editorSession.PowerShellContext.ExecuteCommandAsync <System.Management.Automation.PSObject>(
                    command,
                    sendOutputToHost : false,
                    sendErrorToHost : true);
            }

            protocolEndpoint.Start();
        }
Beispiel #11
0
 /// <summary>
 /// Internal copy constructor
 /// </summary>
 /// <param name="commandToClone"></param>
 internal PSCommand(PSCommand commandToClone)
 {
     _commands = new CommandCollection();
     foreach (Command command in commandToClone.Commands)
     {
         Command clone = command.Clone();
         // Attach the cloned Command to this instance.
         _commands.Add(clone);
         _currentCommand = clone;
     }
 }
        internal Collection<PSObject> InvokeCommand(PSCommand command, ExchContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("Context", "Parametr not defined. [" + _log.Name + "]");
            }

            PSCredential _credential = GetPSCredential(context);

            WSManConnectionInfo _connection = new WSManConnectionInfo(
                new Uri(context.Uri),
                "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
                _credential);
            _connection.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
            _connection.MaximumConnectionRedirectionCount = 3;
            _connection.SkipCACheck = true;
            _connection.SkipCNCheck = true;
            

            using (Runspace _runspace = RunspaceFactory.CreateRunspace(_connection))
            {
                _runspace.Open();
                //_runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "Continue");

                using (PowerShell _powershell = PowerShell.Create())
                {

                    _powershell.Commands = command;

                    try
                    {

                        //RunspaceInvoke _invoker = new RunspaceInvoke(_runspace);
                        //Collection<PSObject> _commandResults = _invoker.Invoke(command.ToString());

                        _powershell.Runspace = _runspace;
                        Collection<PSObject> _commandResults = _powershell.Invoke();
                        CheckErrors(_powershell.Streams.Error);
                        return _commandResults;
                        //foreach (PSObject _result in _commandResults)
                        //{
                        //    Console.WriteLine(_result.ToString());
                        //}

                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message + ". [" + _log.Name + "]");
                    }
                    
                }
            }

        }
        public async Task CanExecutePSCommand()
        {
            PSCommand psCommand = new PSCommand();
            psCommand.AddScript("$a = \"foo\"; $a");

            var executeTask =
                this.powerShellContext.ExecuteCommand<string>(psCommand);

            await this.AssertStateChange(PowerShellContextState.Running);
            await this.AssertStateChange(PowerShellContextState.Ready);

            var result = await executeTask;
            Assert.Equal("foo", result.First());
        }
        /// <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 async Task CanQueueParallelRunspaceRequests()
        {
            // Concurrently initiate 4 requests in the session
            this.powerShellContext.ExecuteScriptString("$x = 100");
            Task<RunspaceHandle> handleTask = this.powerShellContext.GetRunspaceHandle();
            this.powerShellContext.ExecuteScriptString("$x += 200");
            this.powerShellContext.ExecuteScriptString("$x = $x / 100");

            PSCommand psCommand = new PSCommand();
            psCommand.AddScript("$x");
            Task<IEnumerable<int>> resultTask = this.powerShellContext.ExecuteCommand<int>(psCommand);

            // Wait for the requested runspace handle and then dispose it
            RunspaceHandle handle = await handleTask;
            handle.Dispose();

            // At this point, the remaining command executions should execute and complete
            int result = (await resultTask).FirstOrDefault();

            // 100 + 200 = 300, then divided by 100 is 3.  We are ensuring that
            // the commands were executed in the sequence they were called.
            Assert.Equal(3, result);
        }
        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;
        }
        /// <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();
            }
        }
        /// <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<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();
        }
        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());
        }
        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 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 static void SetPowerShellInstance(PowerShell instance)
 {
     PowerShellAgent.PowerShellInstance = instance;
     PowerShellAgent.InitCommand = instance.Commands;
 }
        internal void StartPowerShellCommand(
            PowerShell powershell,
            Guid powershellId,
            Guid runspacePoolId,
            ServerRunspacePoolDriver runspacePoolDriver,
#if !CORECLR // No ApartmentState In CoreCLR
            ApartmentState apartmentState,
#endif
            ServerRemoteHost remoteHost,
            HostInfo hostInfo,
            RemoteStreamOptions streamOptions,
            bool addToHistory)
        {
            // For nested debugger command processing, invoke command on new local runspace since
            // the root script debugger runspace is unavailable (it is running a PS script or a 
            // workflow function script).
            Runspace runspace = (remoteHost != null) ?
                RunspaceFactory.CreateRunspace(remoteHost) : RunspaceFactory.CreateRunspace();

            runspace.Open();

            try
            {
                powershell.InvocationStateChanged += HandlePowerShellInvocationStateChanged;
                powershell.SetIsNested(false);

                string script = @"
                    param ($Debugger, $Commands, $output)
                    trap { throw $_ }
                    $Debugger.ProcessCommand($Commands, $output)
                    ";

                PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
                PSCommand Commands = new PSCommand(powershell.Commands);
                powershell.Commands.Clear();
                powershell.AddScript(script).AddParameter("Debugger", this).AddParameter("Commands", Commands).AddParameter("output", output);
                ServerPowerShellDriver driver = new ServerPowerShellDriver(
                    powershell,
                    null,
                    true,
                    powershellId,
                    runspacePoolId,
                    runspacePoolDriver,
#if !CORECLR // No ApartmentState In CoreCLR
                    apartmentState,
#endif
                    hostInfo,
                    streamOptions,
                    addToHistory,
                    runspace,
                    output);

                driver.Start();
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);

                runspace.Close();
                runspace.Dispose();
            }
        }
Beispiel #27
0
 private PowerShell()
 {
     psCommand = new PSCommand();
     dataStreams = new PSDataStreams(this);
 }
 public ThreadCommandProcessing(
     PSCommand command,
     PSDataCollection<PSObject> output,
     Debugger debugger,
     ManualResetEventSlim processCommandCompleteEvent)
 {
     _command = command;
     _output = output;
     _wrappedDebugger = debugger;
     _commandCompleteEvent = processCommandCompleteEvent;
 }
        /// <summary>
        /// ProcessCommand
        /// </summary>
        /// <param name="command">Command</param>
        /// <param name="output">Output</param>
        /// <returns></returns>
        public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output)
        {
            if (LocalDebugMode)
            {
                return _wrappedDebugger.Value.ProcessCommand(command, output);
            }

            if (!InBreakpoint || (_threadCommandProcessing != null))
            {
                throw new PSInvalidOperationException(
                    StringUtil.Format(DebuggerStrings.CannotProcessDebuggerCommandNotStopped));
            }

            if (_processCommandCompleteEvent == null)
            {
                _processCommandCompleteEvent = new ManualResetEventSlim(false);
            }

            _threadCommandProcessing = new ThreadCommandProcessing(command, output, _wrappedDebugger.Value, _processCommandCompleteEvent);
            try
            {
                return _threadCommandProcessing.Invoke(_nestedDebugStopCompleteEvent);
            }
            finally
            {
                _threadCommandProcessing = null;
            }
        }
        /// <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;
        }
        /// <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();
            }
        }
Beispiel #32
0
 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;
 }
        /// <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();
            }
        }
Beispiel #34
0
 internal BatchInvocationContext(PSCommand command, PSDataCollection <PSObject> output)
 {
     this.command         = command;
     this.output          = output;
     this.completionEvent = new AutoResetEvent(false);
 }