Exemple #1
0
 private void ProcessImportModule(string name, PSModuleInfo moduleInfoToLoad, bool startLifeCycleEventWritten)
 {
     using (PowerShell shell = PowerShell.Create())
     {
         List <ErrorRecord> errors = new List <ErrorRecord>();
         if (!this.InitialSessionState.ThrowOnRunspaceOpenError)
         {
             CommandInfo importModuleCommandInfo = this.GetImportModuleCommandInfo(name, ref errors);
             if (importModuleCommandInfo != null)
             {
                 Command command = new Command(importModuleCommandInfo);
                 if (moduleInfoToLoad != null)
                 {
                     command.Parameters.Add("ModuleInfo", moduleInfoToLoad);
                 }
                 else
                 {
                     command.Parameters.Add("Name", name);
                 }
                 command.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                 shell.AddCommand(command);
                 importModuleCommandInfo = this.GetOutDefaultCommandInfo(name, ref errors);
                 if (importModuleCommandInfo != null)
                 {
                     shell.AddCommand(new Command(importModuleCommandInfo));
                 }
             }
         }
         else
         {
             CommandInfo commandInfo = this.GetImportModuleCommandInfo(name, ref errors);
             if (commandInfo != null)
             {
                 Command command2 = new Command(commandInfo);
                 if (moduleInfoToLoad != null)
                 {
                     command2.Parameters.Add("ModuleInfo", moduleInfoToLoad);
                 }
                 else
                 {
                     command2.Parameters.Add("Name", name);
                 }
                 shell.AddCommand(command2);
             }
         }
         if (((shell.Commands != null) && (shell.Commands.Commands != null)) && (shell.Commands.Commands.Count > 0))
         {
             shell.Runspace = this;
             shell.Invoke();
         }
         this.ValidateAndThrowRunspaceOpenModuleLoadException(shell, errors, startLifeCycleEventWritten, name, null);
     }
 }
Exemple #2
0
        /// <summary>
        /// Creates a Command object from a PSObject property bag.
        /// PSObject has to be in the format returned by ToPSObjectForRemoting method.
        /// </summary>
        /// <param name="commandAsPSObject">PSObject to rehydrate.</param>
        /// <returns>
        /// Command rehydrated from a PSObject property bag
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if the PSObject is null.
        /// </exception>
        /// <exception cref="System.Management.Automation.Remoting.PSRemotingDataStructureException">
        /// Thrown when the PSObject is not in the expected format
        /// </exception>
        internal static Command FromPSObjectForRemoting(PSObject commandAsPSObject)
        {
            if (commandAsPSObject == null)
            {
                throw PSTraceSource.NewArgumentNullException("commandAsPSObject");
            }

            string  commandText           = RemotingDecoder.GetPropertyValue <string>(commandAsPSObject, RemoteDataNameStrings.CommandText);
            bool    isScript              = RemotingDecoder.GetPropertyValue <bool>(commandAsPSObject, RemoteDataNameStrings.IsScript);
            bool?   useLocalScopeNullable = RemotingDecoder.GetPropertyValue <bool?>(commandAsPSObject, RemoteDataNameStrings.UseLocalScopeNullable);
            Command command = new Command(commandText, isScript, useLocalScopeNullable);

            // For V2 backwards compatibility.
            PipelineResultTypes mergeMyResult = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, RemoteDataNameStrings.MergeMyResult);
            PipelineResultTypes mergeToResult = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, RemoteDataNameStrings.MergeToResult);

            command.MergeMyResults(mergeMyResult, mergeToResult);

            command.MergeUnclaimedPreviousCommandResults = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, RemoteDataNameStrings.MergeUnclaimedPreviousCommandResults);

            // V3 merge instructions will not be returned by V2 server and this is expected.
            if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeError] != null)
            {
                command.MergeInstructions[(int)MergeType.Error] = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, RemoteDataNameStrings.MergeError);
            }

            if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeWarning] != null)
            {
                command.MergeInstructions[(int)MergeType.Warning] = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, RemoteDataNameStrings.MergeWarning);
            }

            if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeVerbose] != null)
            {
                command.MergeInstructions[(int)MergeType.Verbose] = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, RemoteDataNameStrings.MergeVerbose);
            }

            if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeDebug] != null)
            {
                command.MergeInstructions[(int)MergeType.Debug] = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, RemoteDataNameStrings.MergeDebug);
            }

            if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeInformation] != null)
            {
                command.MergeInstructions[(int)MergeType.Information] = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, RemoteDataNameStrings.MergeInformation);
            }

            foreach (PSObject parameterAsPSObject in RemotingDecoder.EnumerateListProperty <PSObject>(commandAsPSObject, RemoteDataNameStrings.Parameters))
            {
                command.Parameters.Add(CommandParameter.FromPSObjectForRemoting(parameterAsPSObject));
            }

            return(command);
        }
Exemple #3
0
        internal static Command FromPSObjectForRemoting(PSObject commandAsPSObject)
        {
            if (commandAsPSObject == null)
            {
                throw PSTraceSource.NewArgumentNullException("commandAsPSObject");
            }
            string              propertyValue = RemotingDecoder.GetPropertyValue <string>(commandAsPSObject, "Cmd");
            bool                isScript      = RemotingDecoder.GetPropertyValue <bool>(commandAsPSObject, "IsScript");
            bool?               useLocalScope = RemotingDecoder.GetPropertyValue <bool?>(commandAsPSObject, "UseLocalScope");
            Command             command       = new Command(propertyValue, isScript, useLocalScope);
            PipelineResultTypes myResult      = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, "MergeMyResult");
            PipelineResultTypes toResult      = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, "MergeToResult");

            command.MergeMyResults(myResult, toResult);
            command.MergeUnclaimedPreviousCommandResults = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, "MergePreviousResults");
            if (commandAsPSObject.Properties["MergeError"] != null)
            {
                command.MergeInstructions[0] = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, "MergeError");
            }
            if (commandAsPSObject.Properties["MergeWarning"] != null)
            {
                command.MergeInstructions[1] = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, "MergeWarning");
            }
            if (commandAsPSObject.Properties["MergeVerbose"] != null)
            {
                command.MergeInstructions[2] = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, "MergeVerbose");
            }
            if (commandAsPSObject.Properties["MergeDebug"] != null)
            {
                command.MergeInstructions[3] = RemotingDecoder.GetPropertyValue <PipelineResultTypes>(commandAsPSObject, "MergeDebug");
            }
            foreach (PSObject obj2 in RemotingDecoder.EnumerateListProperty <PSObject>(commandAsPSObject, "Args"))
            {
                command.Parameters.Add(CommandParameter.FromPSObjectForRemoting(obj2));
            }
            return(command);
        }
Exemple #4
0
		public PoshHost(IPSUI psUi)
		{
			_buffer = psUi.Console;
			_tabExpander = new TabExpander(this);

			MakeConsole();

			Options = new PoshOptions(this, _buffer);
			_psUi = psUi;

			try
			{
				// we have to be careful here, because this is an interface member ...
				// but in the current implementation, _buffer.RawUI returns _buffer
				_rawUI = new PoshRawUI(_buffer.RawUI);
				_UI = new PoshUI(_rawUI, psUi);

				// pre-create this
				_outDefault = new Command("Out-Default");
				// for now, merge the errors with the rest of the output
				_outDefault.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
				_outDefault.MergeUnclaimedPreviousCommandResults = PipelineResultTypes.Error | PipelineResultTypes.Output;
			}
			catch (Exception ex)
			{
				MessageBox.Show(
					"Can't create PowerShell interface, are you sure PowerShell is installed? \n" + ex.Message + "\nAt:\n" +
						ex.Source, "Error Starting PoshConsole", MessageBoxButton.OK, MessageBoxImage.Stop);
				throw;
			}
			_buffer.CommandBox.IsEnabled = false;
			_buffer.Expander.TabComplete += _tabExpander.Expand;
			_buffer.Command += OnGotUserInput;

			// Some delegates we think we can get away with making only once...
			Properties.Settings.Default.PropertyChanged += SettingsPropertyChanged;

			_runner = new CommandRunner(this, Resources.Prompt);
			_runner.RunspaceReady += (source, args) => _buffer.Dispatcher.BeginInvoke((Action) (() =>
				{
					_buffer.CommandBox.IsEnabled = true;
					ExecutePromptFunction(null, PipelineState.Completed);
				}));

			_runner.ShouldExit += (source, args) => SetShouldExit(args);
		}
        /// <summary>
        /// Invokes a script
        /// </summary>
        /// <param name="cmdToRun"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private PSDataCollection<PSObject> InvokeScript(Command cmdToRun, RunspaceCreatedEventArgs args)
        {
            Debug.Assert(cmdToRun != null, "cmdToRun shouldn't be null");

            cmdToRun.CommandOrigin = CommandOrigin.Internal;
            cmdToRun.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
            PowerShell powershell = PowerShell.Create();
            powershell.AddCommand(cmdToRun).AddCommand("out-default");

            return InvokePowerShell(powershell, args);
        }
        private void ConvertCommand(CommandAst commandAst, bool isTrustedInput)
        {
            // First need command name.
            var commandName = GetCommandName(commandAst.CommandElements[0], isTrustedInput);

            var command = new Command(commandName, isScript: false, useLocalScope: _createLocalScope);

            // Handle redirections, if any (there can really be just 0 or 1).
            if (commandAst.Redirections.Count > 0)
            {
                Diagnostics.Assert(commandAst.Redirections.Count == 1, "only 1 kind of redirection is supported");
                Diagnostics.Assert(commandAst.Redirections[0] is MergingRedirectionAst, "unexpected redirection type");

                PipelineResultTypes toType = PipelineResultTypes.Output;
                PipelineResultTypes fromType;
                switch (commandAst.Redirections[0].FromStream)
                {
                    case RedirectionStream.Error:
                        fromType = PipelineResultTypes.Error;
                        break;

                    case RedirectionStream.Warning:
                        fromType = PipelineResultTypes.Warning;
                        break;

                    case RedirectionStream.Verbose:
                        fromType = PipelineResultTypes.Verbose;
                        break;

                    case RedirectionStream.Debug:
                        fromType = PipelineResultTypes.Debug;
                        break;

                    case RedirectionStream.Information:
                        fromType = PipelineResultTypes.Information;
                        break;

                    case RedirectionStream.All:
                        fromType = PipelineResultTypes.All;
                        break;

                    default:
                        // Default to Error->Output to be compatible with V2.
                        fromType = PipelineResultTypes.Error;
                        break;
                }

                command.MergeMyResults(fromType, toType);
            }

            _powershell.AddCommand(command);

            // Now the parameters and arguments.
            foreach (var ast in commandAst.CommandElements.Skip(1))
            {
                var exprAst = ast as ExpressionAst;
                if (exprAst != null)
                {
                    VariableExpressionAst variableAst = null;

                    var usingExprAst = ast as UsingExpressionAst;
                    if (usingExprAst != null)
                    {
                        string usingAstKey = PsUtils.GetUsingExpressionKey(usingExprAst);
                        object usingValue = _usingValueMap[usingAstKey];
                        variableAst = usingExprAst.SubExpression as VariableExpressionAst;
                        if (variableAst != null && variableAst.Splatted)
                        {
                            // Support the splatting of a dictionary
                            var parameters = usingValue as System.Collections.IDictionary;
                            if (parameters != null)
                            {
                                _powershell.AddParameters(parameters);
                            }
                            else
                            {
                                // Support the splatting of an array
                                var arguments = usingValue as System.Collections.IEnumerable;
                                if (arguments != null)
                                {
                                    foreach (Object argument in arguments)
                                    {
                                        _powershell.AddArgument(argument);
                                    }
                                }
                                else
                                {
                                    // Splat the object directly.
                                    _powershell.AddArgument(usingValue);
                                }
                            }
                        }
                        else
                        {
                            _powershell.AddArgument(usingValue);
                        }
                        continue;
                    }

                    variableAst = ast as VariableExpressionAst;
                    if (variableAst != null && variableAst.Splatted)
                    {
                        GetSplattedVariable(variableAst);
                    }
                    else
                    {
                        var constantExprAst = ast as ConstantExpressionAst;
                        object argument;
                        if (constantExprAst != null && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constantExprAst.StaticType)))
                        {
                            var commandArgumentText = constantExprAst.Extent.Text;
                            argument = constantExprAst.Value;
                            if (!commandArgumentText.Equals(constantExprAst.Value.ToString(), StringComparison.Ordinal))
                            {
                                // The wrapped number will actually return a PSObject which could end holding a reference to
                                // a typetable, making the object runspace specific.  We should find a better way to avoid
                                // any possibility of sharing problems, though this is unlikely to cause problems.
                                argument = ParserOps.WrappedNumber(argument, commandArgumentText);
                            }
                        }
                        else
                        {
                            if (!isTrustedInput)
                            {
                                try
                                {
                                    argument = GetSafeValueVisitor.GetSafeValue(exprAst, _context, GetSafeValueVisitor.SafeValueContext.GetPowerShell);
                                }
                                catch (System.Exception)
                                {
                                    throw new ScriptBlockToPowerShellNotSupportedException(
                                        "CantConvertWithDynamicExpression",
                                        null,
                                        AutomationExceptions.CantConvertWithDynamicExpression,
                                        exprAst.Extent.Text);
                                }
                            }
                            else
                            {
                                argument = GetExpressionValue(exprAst, isTrustedInput);
                            }
                        }
                        _powershell.AddArgument(argument);
                    }
                }
                else
                {
                    AddParameter((CommandParameterAst)ast, isTrustedInput);
                }
            }
        }
Exemple #7
0
 private void ProcessImportModule(string name, PSModuleInfo moduleInfoToLoad, bool startLifeCycleEventWritten)
 {
     using (PowerShell shell = PowerShell.Create())
     {
         List<ErrorRecord> errors = new List<ErrorRecord>();
         if (!this.InitialSessionState.ThrowOnRunspaceOpenError)
         {
             CommandInfo importModuleCommandInfo = this.GetImportModuleCommandInfo(name, ref errors);
             if (importModuleCommandInfo != null)
             {
                 Command command = new Command(importModuleCommandInfo);
                 if (moduleInfoToLoad != null)
                 {
                     command.Parameters.Add("ModuleInfo", moduleInfoToLoad);
                 }
                 else
                 {
                     command.Parameters.Add("Name", name);
                 }
                 command.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                 shell.AddCommand(command);
                 importModuleCommandInfo = this.GetOutDefaultCommandInfo(name, ref errors);
                 if (importModuleCommandInfo != null)
                 {
                     shell.AddCommand(new Command(importModuleCommandInfo));
                 }
             }
         }
         else
         {
             CommandInfo commandInfo = this.GetImportModuleCommandInfo(name, ref errors);
             if (commandInfo != null)
             {
                 Command command2 = new Command(commandInfo);
                 if (moduleInfoToLoad != null)
                 {
                     command2.Parameters.Add("ModuleInfo", moduleInfoToLoad);
                 }
                 else
                 {
                     command2.Parameters.Add("Name", name);
                 }
                 shell.AddCommand(command2);
             }
         }
         if (((shell.Commands != null) && (shell.Commands.Commands != null)) && (shell.Commands.Commands.Count > 0))
         {
             shell.Runspace = this;
             shell.Invoke();
         }
         this.ValidateAndThrowRunspaceOpenModuleLoadException(shell, errors, startLifeCycleEventWritten, name, null);
     }
 }
Exemple #8
0
 internal static Command FromPSObjectForRemoting(PSObject commandAsPSObject)
 {
     if (commandAsPSObject == null)
     {
         throw PSTraceSource.NewArgumentNullException("commandAsPSObject");
     }
     string propertyValue = RemotingDecoder.GetPropertyValue<string>(commandAsPSObject, "Cmd");
     bool isScript = RemotingDecoder.GetPropertyValue<bool>(commandAsPSObject, "IsScript");
     bool? useLocalScope = RemotingDecoder.GetPropertyValue<bool?>(commandAsPSObject, "UseLocalScope");
     Command command = new Command(propertyValue, isScript, useLocalScope);
     PipelineResultTypes myResult = RemotingDecoder.GetPropertyValue<PipelineResultTypes>(commandAsPSObject, "MergeMyResult");
     PipelineResultTypes toResult = RemotingDecoder.GetPropertyValue<PipelineResultTypes>(commandAsPSObject, "MergeToResult");
     command.MergeMyResults(myResult, toResult);
     command.MergeUnclaimedPreviousCommandResults = RemotingDecoder.GetPropertyValue<PipelineResultTypes>(commandAsPSObject, "MergePreviousResults");
     if (commandAsPSObject.Properties["MergeError"] != null)
     {
         command.MergeInstructions[0] = RemotingDecoder.GetPropertyValue<PipelineResultTypes>(commandAsPSObject, "MergeError");
     }
     if (commandAsPSObject.Properties["MergeWarning"] != null)
     {
         command.MergeInstructions[1] = RemotingDecoder.GetPropertyValue<PipelineResultTypes>(commandAsPSObject, "MergeWarning");
     }
     if (commandAsPSObject.Properties["MergeVerbose"] != null)
     {
         command.MergeInstructions[2] = RemotingDecoder.GetPropertyValue<PipelineResultTypes>(commandAsPSObject, "MergeVerbose");
     }
     if (commandAsPSObject.Properties["MergeDebug"] != null)
     {
         command.MergeInstructions[3] = RemotingDecoder.GetPropertyValue<PipelineResultTypes>(commandAsPSObject, "MergeDebug");
     }
     foreach (PSObject obj2 in RemotingDecoder.EnumerateListProperty<PSObject>(commandAsPSObject, "Args"))
     {
         command.Parameters.Add(CommandParameter.FromPSObjectForRemoting(obj2));
     }
     return command;
 }
        private void ConvertCommand(CommandAst commandAst)
        {
            Command command = new Command(this.GetCommandName(commandAst.CommandElements[0]), false, this._createLocalScope);
            if (commandAst.Redirections.Count > 0)
            {
                PipelineResultTypes all;
                PipelineResultTypes output = PipelineResultTypes.Output;
                switch (commandAst.Redirections[0].FromStream)
                {
                    case RedirectionStream.All:
                        all = PipelineResultTypes.All;
                        break;

                    case RedirectionStream.Error:
                        all = PipelineResultTypes.Error;
                        break;

                    case RedirectionStream.Warning:
                        all = PipelineResultTypes.Warning;
                        break;

                    case RedirectionStream.Verbose:
                        all = PipelineResultTypes.Verbose;
                        break;

                    case RedirectionStream.Debug:
                        all = PipelineResultTypes.Debug;
                        break;

                    default:
                        all = PipelineResultTypes.Error;
                        break;
                }
                command.MergeMyResults(all, output);
            }
            this._powershell.AddCommand(command);
            foreach (CommandElementAst ast in commandAst.CommandElements.Skip<CommandElementAst>(1))
            {
                ExpressionAst exprAst = ast as ExpressionAst;
                if (exprAst != null)
                {
                    VariableExpressionAst variableAst = null;
                    UsingExpressionAst ast4 = ast as UsingExpressionAst;
                    if (ast4 != null)
                    {
                        variableAst = ast4.SubExpression as VariableExpressionAst;
                        if ((variableAst != null) && variableAst.Splatted)
                        {
                            IDictionary parameters = this._usingValues[ast4.RuntimeUsingIndex] as IDictionary;
                            if (parameters != null)
                            {
                                this._powershell.AddParameters(parameters);
                            }
                            else
                            {
                                IEnumerable enumerable = this._usingValues[ast4.RuntimeUsingIndex] as IEnumerable;
                                if (enumerable != null)
                                {
                                    foreach (object obj2 in enumerable)
                                    {
                                        this._powershell.AddArgument(obj2);
                                    }
                                }
                                else
                                {
                                    this._powershell.AddArgument(this._usingValues[ast4.RuntimeUsingIndex]);
                                }
                            }
                        }
                        else
                        {
                            this._powershell.AddArgument(this._usingValues[ast4.RuntimeUsingIndex]);
                        }
                    }
                    else
                    {
                        variableAst = ast as VariableExpressionAst;
                        if ((variableAst != null) && variableAst.Splatted)
                        {
                            this.GetSplattedVariable(variableAst);
                        }
                        else
                        {
                            object expressionValue;
                            ConstantExpressionAst ast5 = ast as ConstantExpressionAst;
                            if ((ast5 != null) && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(ast5.StaticType)))
                            {
                                string text = ast5.Extent.Text;
                                expressionValue = ast5.Value;
                                if (!text.Equals(ast5.Value.ToString(), StringComparison.Ordinal))
                                {
                                    expressionValue = ParserOps.WrappedNumber(expressionValue, text);
                                }
                            }
                            else
                            {
                                expressionValue = this.GetExpressionValue(exprAst);
                            }
                            this._powershell.AddArgument(expressionValue);
                        }
                    }
                }
                else
                {
                    this.AddParameter((CommandParameterAst) ast);
                }
            }
        }
 private PSDataCollection<PSObject> InvokeScript(Command cmdToRun, RunspaceCreatedEventArgs args)
 {
     cmdToRun.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
     PowerShell powershell = PowerShell.Create();
     powershell.AddCommand(cmdToRun).AddCommand("out-default");
     return this.InvokePowerShell(powershell, args);
 }