Ejemplo n.º 1
0
		internal Collection<PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, Executor.ExecutionOptions options)
		{
			exceptionThrown = null;
			Collection<PSObject> pSObjects = null;
			if ((options & Executor.ExecutionOptions.AddOutputter) > Executor.ExecutionOptions.None)
			{
				if (tempPipeline.Commands.Count == 1)
				{
					tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
				}
				Command command = new Command("Out-Default", false, new bool?(true), true);
				tempPipeline.Commands.Add(command);
			}
			lock (this.instanceStateLock)
			{
				this.pipeline = tempPipeline;
			}
			try
			{
				try
				{
					pSObjects = tempPipeline.Invoke();
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					PowwaHost.CheckForSevereException(exception);
					exceptionThrown = exception;
				}
			}
			finally
			{
				this.parent.ResetProgress();
				this.Reset();
			}
			return pSObjects;
		}
Ejemplo n.º 2
0
        /// <summary>
        /// 
        /// Loops over the Host's sole Runspace; opens the runspace, initializes it, then recycles it if the Runspace fails.
        /// 
        /// </summary>
        /// <returns>
        /// 
        /// The process exit code to be returned by Main.
        /// 
        /// </returns>
        private uint DoRunspaceLoop(string initialCommand, bool skipProfiles, Collection<CommandParameter> initialCommandArgs, bool staMode,
            bool importSystemModules, string configurationName)
        {
            ExitCode = ExitCodeSuccess;

            while (!ShouldEndSession)
            {
                RunspaceCreationEventArgs args = new RunspaceCreationEventArgs(initialCommand, skipProfiles, staMode, importSystemModules, configurationName, initialCommandArgs);
                CreateRunspace(args);

                if (ExitCode == ExitCodeInitFailure) { break; }

                if (!_noExit)
                {
                    // Wait for runspace to open, init, and run init script before 
                    // setting ShouldEndSession, to allow debugger to work.
                    ShouldEndSession = true;
                }
                else
                {
                    // Start nested prompt loop.
                    EnterNestedPrompt();
                }

                if (_setShouldExitCalled)
                {
                    ExitCode = unchecked((uint)_exitCodeFromRunspace);
                }
                else
                {
                    Executor exec = new Executor(this, false, false);

                    bool dollarHook = exec.ExecuteCommandAndGetResultAsBool("$global:?") ?? false;

                    if (dollarHook && (_lastRunspaceInitializationException == null))
                    {
                        ExitCode = ExitCodeSuccess;
                    }
                    else
                    {
                        ExitCode = ExitCodeSuccess | 0x1;
                    }
                }

                _runspaceRef.Runspace.Close();
                _runspaceRef = null;
                if (staMode) // don't recycle the Runspace in STA mode
                {
                    ShouldEndSession = true;
                }
            }

            return ExitCode;
        }
Ejemplo n.º 3
0
		internal void ExecuteCommandAsync(string command, out Exception exceptionThrown, Executor.ExecutionOptions options)
		{
			bool flag = (options & Executor.ExecutionOptions.AddToHistory) > Executor.ExecutionOptions.None;
			Pipeline pipeline = this.parent.RunspaceRef.CreatePipeline(command, flag, false);
			this.ExecuteCommandAsyncHelper(pipeline, out exceptionThrown, options);
		}
Ejemplo n.º 4
0
		internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exceptionThrown, Executor.ExecutionOptions options)
		{
			exceptionThrown = null;
			lock (this.instanceStateLock)
			{
				this.pipeline = tempPipeline;
			}
			try
			{
				try
				{
					if ((options & Executor.ExecutionOptions.AddOutputter) > Executor.ExecutionOptions.None && this.parent.OutputFormat == Serialization.DataFormat.Text)
					{
						if (tempPipeline.Commands.Count == 1)
						{
							tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
						}
						Command command = new Command("Out-Default", false, true);
						tempPipeline.Commands.Add(command);
					}
					tempPipeline.Output.DataReady += new EventHandler(this.OutputObjectStreamHandler);
					tempPipeline.Error.DataReady += new EventHandler(this.ErrorObjectStreamHandler);
					tempPipeline.StateChanged += HandleStateChanged;
					tempPipeline.InvokeAsync();
					if ((options & Executor.ExecutionOptions.ReadInputObjects) > Executor.ExecutionOptions.None && this.parent.IsStandardInputRedirected)
					{
						WrappedDeserializer wrappedDeserializer = new WrappedDeserializer(this.parent.InputFormat, "Input", this.parent.StandardInReader);
						while (!wrappedDeserializer.AtEnd)
						{
							object obj = wrappedDeserializer.Deserialize();
							if (obj == null)
							{
								break;
							}
							try
							{
								tempPipeline.Input.Write(obj);
							}
							catch (PipelineClosedException pipelineClosedException)
							{
								break;
							}
						}
						wrappedDeserializer.End();
					}
					tempPipeline.Input.Close();
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					PowwaHost.CheckForSevereException(exception);
					exceptionThrown = exception;
				}
			}
			finally
			{
				this.parent.ResetProgress();
				this.Reset();
			}
		}
Ejemplo n.º 5
0
 private InputLoop(ConsoleHost parent, bool isNested)
 {
     _parent = parent;
     _isNested = isNested;
     _isRunspacePushed = parent.IsRunspacePushed;
     parent.RunspacePopped += new EventHandler(HandleRunspacePopped);
     parent.RunspacePushed += new EventHandler(HandleRunspacePushed);
     _exec = new Executor(parent, isNested, false);
     _promptExec = new Executor(parent, isNested, true);
 }
Ejemplo n.º 6
0
        internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exceptionThrown, Executor.ExecutionOptions options)
        {
            exceptionThrown = null;
            Executor currentExecutor = Executor.CurrentExecutor;

            Executor.CurrentExecutor = this;
            lock (this.instanceStateLock)
            {
                this.pipeline = tempPipeline;
            }
            try
            {
                try
                {
                    if ((options & Executor.ExecutionOptions.AddOutputter) > Executor.ExecutionOptions.None && this.parent.OutputFormat == Serialization.DataFormat.Text)
                    {
                        if (tempPipeline.Commands.Count == 1)
                        {
                            tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                        }
                        Command command = new Command("Out-Default", false, true);
                        tempPipeline.Commands.Add(command);
                    }
                    tempPipeline.Output.DataReady += new EventHandler(this.OutputObjectStreamHandler);
                    tempPipeline.Error.DataReady  += new EventHandler(this.ErrorObjectStreamHandler);
                    Executor.PipelineFinishedWaitHandle pipelineFinishedWaitHandle = new Executor.PipelineFinishedWaitHandle(tempPipeline);
                    tempPipeline.InvokeAsync();
                    if ((options & Executor.ExecutionOptions.ReadInputObjects) > Executor.ExecutionOptions.None && this.parent.IsStandardInputRedirected)
                    {
                        WrappedDeserializer wrappedDeserializer = new WrappedDeserializer(this.parent.InputFormat, "Input", this.parent.StandardInReader);
                        while (!wrappedDeserializer.AtEnd)
                        {
                            object obj = wrappedDeserializer.Deserialize();
                            if (obj == null)
                            {
                                break;
                            }
                            try
                            {
                                tempPipeline.Input.Write(obj);
                            }
                            catch (PipelineClosedException pipelineClosedException)
                            {
                                break;
                            }
                        }
                        wrappedDeserializer.End();
                    }
                    tempPipeline.Input.Close();
                    pipelineFinishedWaitHandle.Wait();
                    if (tempPipeline.PipelineStateInfo.State == PipelineState.Failed && tempPipeline.PipelineStateInfo.Reason != null)
                    {
                        if (this.parent.OutputFormat != Serialization.DataFormat.Text)
                        {
                            this.AsyncPipelineFailureHandler(tempPipeline.PipelineStateInfo.Reason);
                        }
                        else
                        {
                            exceptionThrown = tempPipeline.PipelineStateInfo.Reason;
                        }
                    }
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    ConsoleHost.CheckForSevereException(exception);
                    exceptionThrown = exception;
                }
            }
            finally
            {
                this.parent.ui.ResetProgress();
                Executor.CurrentExecutor = currentExecutor;
                this.Reset();
            }
        }
Ejemplo n.º 7
0
			private InputLoop(ConsoleHost parent, bool isNested)
			{
				this.syncObject = new object();
				this.parent = parent;
				this.isNested = isNested;
				this.isRunspacePushed = parent.IsRunspacePushed;
				parent.RunspacePopped += new EventHandler(this.HandleRunspacePopped);
				parent.RunspacePushed += new EventHandler(this.HandleRunspacePushed);
				this.exec = new Executor(parent, isNested, false);
				this.promptExec = new Executor(parent, isNested, true);
			}
Ejemplo n.º 8
0
        private void RunProfile(string profileFileName, Executor exec)
        {
            if (!String.IsNullOrEmpty(profileFileName))
            {
                s_runspaceInitTracer.WriteLine("checking profile" + profileFileName);

                try
                {
                    if (File.Exists(profileFileName))
                    {
                        InitializeRunspaceHelper(
                            ". '" + EscapeSingleQuotes(profileFileName) + "'",
                            exec,
                            Executor.ExecutionOptions.AddOutputter);
                    }
                    else
                    {
                        s_runspaceInitTracer.WriteLine("profile file not found");
                    }
                }
                catch (Exception e) // Catch-all OK, 3rd party callout
                {
                    CommandProcessorBase.CheckForSevereException(e);
                    ReportException(e, exec);

                    s_runspaceInitTracer.WriteLine("Could not load profile.");
                }
            }
        }
Ejemplo n.º 9
0
		private void ReportException(Exception e, Executor exec)
		{
			object errorRecord;
			Pipeline pipeline = exec.CreatePipeline();
			IContainsErrorRecord containsErrorRecord = e as IContainsErrorRecord;
			if (containsErrorRecord == null)
			{
				errorRecord = new ErrorRecord(e, "ConsoleHost.ReportException", ErrorCategory.NotSpecified, null);
			}
			else
			{
				errorRecord = containsErrorRecord.ErrorRecord;
			}
			PSObject pSObject = new PSObject(errorRecord);
			PSNoteProperty pSNoteProperty = new PSNoteProperty("writeErrorStream", true);
			pSObject.Properties.Add(pSNoteProperty);
			Exception exception = null;
			pipeline.Input.Write(pSObject);
			if (!this.IsRunningAsync)
			{
				exec.ExecuteCommandHelper(pipeline, out exception, Executor.ExecutionOptions.AddOutputter);
			}
			else
			{
				exec.ExecuteCommandAsyncHelper(pipeline, out exception, Executor.ExecutionOptions.AddOutputter);
			}
			if (exception != null)
			{
				this.ReportExceptionFallback(e, null);
			}
		}
Ejemplo n.º 10
0
		private void RunProfile(string profileFileName, Executor exec)
		{
			if (!string.IsNullOrEmpty(profileFileName))
			{
				ConsoleHost.runspaceInitTracer.WriteLine(string.Concat("checking profile", profileFileName), new object[0]);
				try
				{
					if (!File.Exists(profileFileName))
					{
						ConsoleHost.runspaceInitTracer.WriteLine("profile file not found", new object[0]);
					}
					else
					{
						this.InitializeRunspaceHelper(string.Concat(". '", ConsoleHost.EscapeSingleQuotes(profileFileName), "'"), exec, Executor.ExecutionOptions.AddOutputter);
					}
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					CommandProcessorBase.CheckForSevereException(exception);
					this.ReportException(exception, exec);
					ConsoleHost.runspaceInitTracer.WriteLine("Could not load profile.", new object[0]);
				}
			}
		}
Ejemplo n.º 11
0
		private Exception InitializeRunspaceHelper(string command, Executor exec, Executor.ExecutionOptions options)
		{
			ConsoleHost.runspaceInitTracer.WriteLine(string.Concat("running command ", command), new object[0]);
			Exception exception = null;
			if (!this.IsRunningAsync)
			{
				exec.ExecuteCommand(command, out exception, options);
			}
			else
			{
				exec.ExecuteCommandAsync(command, out exception, options);
			}
			if (exception != null)
			{
				this.ReportException(exception, exec);
			}
			return exception;
		}
Ejemplo n.º 12
0
        internal Collection <PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options)
        {
            Dbg.Assert(tempPipeline != null, "command should have a value");

            exceptionThrown = null;

            Collection <PSObject> results = null;

            if ((options & ExecutionOptions.AddOutputter) > 0)
            {
                if (tempPipeline.Commands.Count < 2)
                {
                    if (tempPipeline.Commands.Count == 1)
                    {
                        // Tell the script command to merge it's output and error streams.
                        tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    }

                    // Add Out-Default to the pipeline to render.
                    tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement: false));
                }
                else
                {
                    // For multiple commands/scripts we need to insert Out-Default at the end of each statement.
                    CommandCollection executeCommands = new CommandCollection();
                    foreach (var cmd in tempPipeline.Commands)
                    {
                        executeCommands.Add(cmd);

                        if (cmd.IsEndOfStatement)
                        {
                            // End of statement needs to pipe to Out-Default.
                            cmd.IsEndOfStatement = false;
                            executeCommands.Add(GetOutDefaultCommand(endOfStatement: true));
                        }
                    }

                    var lastCmd = executeCommands.Last();
                    if (!((lastCmd.CommandText != null) &&
                          (lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase)))
                        )
                    {
                        // Ensure pipeline output goes to Out-Default.
                        executeCommands.Add(GetOutDefaultCommand(endOfStatement: false));
                    }

                    tempPipeline.Commands.Clear();
                    foreach (var cmd in executeCommands)
                    {
                        tempPipeline.Commands.Add(cmd);
                    }
                }
            }

            Executor oldCurrent = CurrentExecutor;

            CurrentExecutor = this;

            lock (_instanceStateLock)
            {
                Dbg.Assert(_pipeline == null, "no other pipeline should exist");
                _pipeline = tempPipeline;
            }

            try
            {
                // blocks until all results are retrieved.
                results = tempPipeline.Invoke();
            }
            catch (Exception e)
            {
                exceptionThrown = e;
            }
            finally
            {
                // Once we have the results, or an exception is thrown, we throw away the pipeline.

                _parent.ui.ResetProgress();
                CurrentExecutor = oldCurrent;
                Reset();
            }

            return(results);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Executes a pipeline in the console when we are running asnyc.
        /// </summary>
        /// <param name="tempPipeline">
        /// The pipeline to execute.
        /// </param>
        /// <param name="exceptionThrown">
        /// Any exception thrown trying to run the pipeline.
        /// </param>
        /// <param name="options">
        /// The options to use to execute the pipeline.
        /// </param>
        internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options)
        {
            Dbg.Assert(!_isPromptFunctionExecutor, "should not async invoke the prompt");

            exceptionThrown = null;
            Executor oldCurrent = CurrentExecutor;

            CurrentExecutor = this;

            lock (_instanceStateLock)
            {
                Dbg.Assert(_pipeline == null, "no other pipeline should exist");
                _pipeline = tempPipeline;
            }

            try
            {
                if ((options & ExecutionOptions.AddOutputter) > 0 && _parent.OutputFormat == Serialization.DataFormat.Text)
                {
                    // Tell the script command to merge it's output and error streams

                    if (tempPipeline.Commands.Count == 1)
                    {
                        tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                    }

                    // then add out-default to the pipeline to render everything...
                    Command outDefault = new Command("Out-Default", /* isScript */ false, /* useLocalScope */ true);
                    tempPipeline.Commands.Add(outDefault);
                }

                tempPipeline.Output.DataReady += new EventHandler(OutputObjectStreamHandler);
                tempPipeline.Error.DataReady  += new EventHandler(ErrorObjectStreamHandler);
                PipelineFinishedWaitHandle pipelineWaiter = new PipelineFinishedWaitHandle(tempPipeline);

                // close the input pipeline so the command will do something
                // if we are not reading input
                if ((options & Executor.ExecutionOptions.ReadInputObjects) == 0)
                {
                    tempPipeline.Input.Close();
                }

                tempPipeline.InvokeAsync();
                if ((options & ExecutionOptions.ReadInputObjects) > 0 && Console.IsInputRedirected)
                {
                    // read input objects from stdin
                    WrappedDeserializer des = new WrappedDeserializer(_parent.InputFormat, "Input", _parent.ConsoleIn.Value);
                    while (!des.AtEnd)
                    {
                        object o = des.Deserialize();
                        if (o == null)
                        {
                            break;
                        }

                        try
                        {
                            tempPipeline.Input.Write(o);
                        }
                        catch (PipelineClosedException)
                        {
                            //This exception can occurs when input is closed. This can happen
                            //for various reasons. For ex:Command in the pipeline is invalid and
                            //command discovery throws exception which closes the pipeline and
                            //hence the Input pipe.
                            break;
                        }
                    }
                    ;
                    des.End();
                }

                tempPipeline.Input.Close();

                pipelineWaiter.Wait();

                //report error if pipeline failed
                if (tempPipeline.PipelineStateInfo.State == PipelineState.Failed && tempPipeline.PipelineStateInfo.Reason != null)
                {
                    if (_parent.OutputFormat == Serialization.DataFormat.Text)
                    {
                        //Report the exception using normal error reporting
                        exceptionThrown = tempPipeline.PipelineStateInfo.Reason;
                    }
                    else
                    {
                        //serialize the error record
                        AsyncPipelineFailureHandler(tempPipeline.PipelineStateInfo.Reason);
                    }
                }
            }
            catch (Exception e)
            {
                exceptionThrown = e;
            }
            finally
            {
                // Once we have the results, or an exception is thrown, we throw away the pipeline.

                _parent.ui.ResetProgress();
                CurrentExecutor = oldCurrent;
                Reset();
            }
        }
Ejemplo n.º 14
0
        private Exception InitializeRunspaceHelper(string command, Executor exec, Executor.ExecutionOptions options)
        {
            Dbg.Assert(!String.IsNullOrEmpty(command), "command should have a value");
            Dbg.Assert(exec != null, "non-null Executor instance needed");

            s_runspaceInitTracer.WriteLine("running command {0}", command);

            Exception e = null;

            if (IsRunningAsync)
            {
                exec.ExecuteCommandAsync(command, out e, options);
            }
            else
            {
                exec.ExecuteCommand(command, out e, options);
            }
            if (e != null)
            {
                ReportException(e, exec);
            }

            return e;
        }
Ejemplo n.º 15
0
		private void DoRunspaceInitialization(bool importSystemModules, bool skipProfiles, string initialCommand, Collection<CommandParameter> initialCommandArgs)
		{
			string shellId;
			Exception exception = null;
			Token[] tokenArray = null;
			ParseError[] parseErrorArray = null;
			Exception exception1 = null;
			Token[] tokenArray1 = null;
			ParseError[] parseErrorArray1 = null;
			this.runspaceRef.Runspace.Debugger.DebuggerStop += new EventHandler<DebuggerStopEventArgs>(this.OnExecutionSuspended);
			Executor executor = new Executor(this, false, false);
			if (importSystemModules)
			{
				this.InitializeRunspaceHelper("ImportSystemModules", executor, Executor.ExecutionOptions.None);
			}
			RunspaceConfigurationEntryCollection<ScriptConfigurationEntry> scriptConfigurationEntries = new RunspaceConfigurationEntryCollection<ScriptConfigurationEntry>();
			if (this.configuration != null)
			{
				scriptConfigurationEntries = this.configuration.InitializationScripts;
			}
			if (scriptConfigurationEntries == null || scriptConfigurationEntries.Count == 0)
			{
				ConsoleHost.runspaceInitTracer.WriteLine("There are no built-in scripts to run", new object[0]);
			}
			else
			{
				foreach (ScriptConfigurationEntry scriptConfigurationEntry in scriptConfigurationEntries)
				{
					object[] name = new object[1];
					name[0] = scriptConfigurationEntry.Name;
					ConsoleHost.runspaceInitTracer.WriteLine("Running script: '{0}'", name);
					try
					{
						this.isCtrlCDisabled = true;
						Exception exception2 = this.InitializeRunspaceHelper(scriptConfigurationEntry.Definition, executor, Executor.ExecutionOptions.AddOutputter);
						if (exception2 != null)
						{
							throw new ConsoleHost.ConsoleHostStartupException(ConsoleHostStrings.InitScriptFailed, exception2);
						}
					}
					finally
					{
						this.isCtrlCDisabled = false;
					}
				}
			}
			if (this.configuration == null)
			{
				shellId = "Microsoft.PowerShell";
			}
			else
			{
				shellId = this.configuration.ShellId;
			}
			if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
			{
				this.runspaceRef.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
			}
			string fullProfileFileName = HostUtilities.GetFullProfileFileName(null, false);
			string str = HostUtilities.GetFullProfileFileName(shellId, false);
			string fullProfileFileName1 = HostUtilities.GetFullProfileFileName(null, true);
			string str1 = HostUtilities.GetFullProfileFileName(shellId, true);
			this.runspaceRef.Runspace.SessionStateProxy.SetVariable("PROFILE", HostUtilities.GetDollarProfile(fullProfileFileName, str, fullProfileFileName1, str1));
			if (skipProfiles)
			{
				ConsoleHost.tracer.WriteLine("-noprofile option specified: skipping profiles", new object[0]);
			}
			else
			{
				this.RunProfile(fullProfileFileName, executor);
				this.RunProfile(str, executor);
				this.RunProfile(fullProfileFileName1, executor);
				this.RunProfile(str1, executor);
			}
			if (ConsoleHost.cpp == null || ConsoleHost.cpp.File == null)
			{
				if (!string.IsNullOrEmpty(initialCommand))
				{
					ConsoleHost.tracer.WriteLine("running initial command", new object[0]);
					Pipeline pipeline = executor.CreatePipeline(initialCommand, true);
					if (initialCommandArgs != null)
					{
						foreach (CommandParameter initialCommandArg in initialCommandArgs)
						{
							pipeline.Commands[0].Parameters.Add(initialCommandArg);
						}
					}
					if (!this.IsRunningAsync)
					{
						executor.ExecuteCommandHelper(pipeline, out exception1, Executor.ExecutionOptions.AddOutputter);
					}
					else
					{
						Executor.ExecutionOptions executionOption = Executor.ExecutionOptions.AddOutputter;
						Ast ast = Parser.ParseInput(initialCommand, out tokenArray1, out parseErrorArray1);
						if (AstSearcher.IsUsingDollarInput(ast))
						{
							executionOption = executionOption | Executor.ExecutionOptions.ReadInputObjects;
						}
						executor.ExecuteCommandAsyncHelper(pipeline, out exception1, executionOption);
					}
					if (exception1 != null)
					{
						this.ReportException(exception1, executor);
					}
				}
			}
			else
			{
				string file = ConsoleHost.cpp.File;
				object[] objArray = new object[1];
				objArray[0] = file;
				ConsoleHost.tracer.WriteLine("running -file '{0}'", objArray);
				Pipeline pipeline1 = executor.CreatePipeline();
				Command command = new Command(file, false, false);
				pipeline1.Commands.Add(command);
				if (initialCommandArgs != null)
				{
					foreach (CommandParameter commandParameter in initialCommandArgs)
					{
						command.Parameters.Add(commandParameter);
					}
				}
				if (!this.noExit)
				{
					this.Runspace.ExecutionContext.ScriptCommandProcessorShouldRethrowExit = true;
				}
				if (!this.IsRunningAsync)
				{
					executor.ExecuteCommandHelper(pipeline1, out exception, Executor.ExecutionOptions.AddOutputter);
				}
				else
				{
					Executor.ExecutionOptions executionOption1 = Executor.ExecutionOptions.AddOutputter;
					Ast ast1 = Parser.ParseFile(file, out tokenArray, out parseErrorArray);
					if (AstSearcher.IsUsingDollarInput(ast1))
					{
						executionOption1 = executionOption1 | Executor.ExecutionOptions.ReadInputObjects;
					}
					executor.ExecuteCommandAsyncHelper(pipeline1, out exception, executionOption1);
				}
				if (exception != null)
				{
					this.ReportException(exception, executor);
					return;
				}
			}
		}
Ejemplo n.º 16
0
        private void DoRunspaceInitialization(bool importSystemModules, bool skipProfiles, string initialCommand, string configurationName, Collection<CommandParameter> initialCommandArgs)
        {
            if (_runspaceRef.Runspace.Debugger != null)
            {
                _runspaceRef.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);
                _runspaceRef.Runspace.Debugger.DebuggerStop += this.OnExecutionSuspended;
            }

            Executor exec = new Executor(this, false, false);

            // Run import system modules command
            if (importSystemModules)
            {
                Exception exception = InitializeRunspaceHelper("ImportSystemModules", exec, Executor.ExecutionOptions.None);
            }

            if (!string.IsNullOrEmpty(configurationName))
            {
                // If an endpoint configuration is specified then create a loop-back remote runspace targeting
                // the endpoint and push onto runspace ref stack.  Ignore profile and configuration scripts.
                try
                {
                    RemoteRunspace remoteRunspace = HostUtilities.CreateConfiguredRunspace(configurationName, this);
                    remoteRunspace.ShouldCloseOnPop = true;
                    PushRunspace(remoteRunspace);

                    // Ensure that session ends when configured remote runspace is popped.
                    _inPushedConfiguredSession = true;
                }
                catch (Exception e)
                {
                    throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStarted, e);
                }
            }
            else
            {
                // Run the built-in scripts
                RunspaceConfigurationEntryCollection<ScriptConfigurationEntry> scripts = new RunspaceConfigurationEntryCollection<ScriptConfigurationEntry>();
                if (_configuration != null)
                    scripts = _configuration.InitializationScripts;

                if ((scripts == null) || (scripts.Count == 0))
                {
                    s_runspaceInitTracer.WriteLine("There are no built-in scripts to run");
                }
                else
                {
                    foreach (ScriptConfigurationEntry s in scripts)
                    {
                        s_runspaceInitTracer.WriteLine("Running script: '{0}'", s.Name);

                        // spec claims that Ctrl-C is not supposed to stop these.

                        try
                        {
                            _isCtrlCDisabled = true;
                            Exception e = InitializeRunspaceHelper(s.Definition, exec, Executor.ExecutionOptions.AddOutputter);
                            if (e != null)
                            {
                                throw new ConsoleHostStartupException(ConsoleHostStrings.InitScriptFailed, e);
                            }
                        }
                        finally
                        {
                            _isCtrlCDisabled = false;
                        }
                    }
                }

                // If -iss has been specified, then there won't be a runspace
                // configuration to get the shell ID from, so we'll use the default...
                string shellId = null;
                if (_configuration != null)
                    shellId = _configuration.ShellId;
                else
                    shellId = "Microsoft.PowerShell"; // TODO: what will happen for custom shells built using Make-Shell.exe

                // If the system lockdown policy says "Enforce", do so. Do this after types / formatting, default functions, etc
                // are loaded so that they are trusted. (Validation of their signatures is done in F&O)
                if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
                {
                    _runspaceRef.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                }

                string allUsersProfile = HostUtilities.GetFullProfileFileName(null, false);
                string allUsersHostSpecificProfile = HostUtilities.GetFullProfileFileName(shellId, false);
                string currentUserProfile = HostUtilities.GetFullProfileFileName(null, true);
                string currentUserHostSpecificProfile = HostUtilities.GetFullProfileFileName(shellId, true);

                // $PROFILE has to be set from the host
                // Should be "per-user,host-specific profile.ps1"
                // This should be set even if -noprofile is specified
                _runspaceRef.Runspace.SessionStateProxy.SetVariable("PROFILE",
                    HostUtilities.GetDollarProfile(
                        allUsersProfile,
                        allUsersHostSpecificProfile,
                        currentUserProfile,
                        currentUserHostSpecificProfile));

                if (!skipProfiles)
                {
                    // Run the profiles.
                    // Profiles are run in the following order:
                    // 1. host independent profile meant for all users
                    // 2. host specific profile meant for all users
                    // 3. host independent profile of the current user
                    // 4. host specific profile  of the current user

                    var sw = new Stopwatch();
                    sw.Start();
                    RunProfile(allUsersProfile, exec);
                    RunProfile(allUsersHostSpecificProfile, exec);
                    RunProfile(currentUserProfile, exec);
                    RunProfile(currentUserHostSpecificProfile, exec);
                    sw.Stop();

                    var profileLoadTimeInMs = sw.ElapsedMilliseconds;
                    if (profileLoadTimeInMs > 500 && s_cpp.ShowBanner)
                    {
                        Console.Error.WriteLine(ConsoleHostStrings.SlowProfileLoadingMessage, profileLoadTimeInMs);
                    }

                    _profileLoadTimeInMS = profileLoadTimeInMs;
                }
                else
                {
                    s_tracer.WriteLine("-noprofile option specified: skipping profiles");
                }
            }

            // Startup is reported after possibly running the profile, but before running the initial command (or file)
            // if one is specified.
            TelemetryAPI.ReportStartupTelemetry(this);

            // If a file was specified as the argument to run, then run it...
            if (s_cpp != null && s_cpp.File != null)
            {
                string filePath = s_cpp.File;

                s_tracer.WriteLine("running -file '{0}'", filePath);

                Pipeline tempPipeline = exec.CreatePipeline();
                Command c = new Command(filePath, false, false);
                tempPipeline.Commands.Add(c);

                if (initialCommandArgs != null)
                {
                    // add the args passed to the command.

                    foreach (CommandParameter p in initialCommandArgs)
                    {
                        c.Parameters.Add(p);
                    }
                }

                // If we're not going to continue, then get the exit code out of the runspace and
                // and indicate that it should be returned...
                if (!_noExit && !(this.Runspace is RemoteRunspace))
                {
                    this.Runspace.ExecutionContext.ScriptCommandProcessorShouldRethrowExit = true;
                }

                Exception e1;

                if (IsRunningAsync)
                {
                    Executor.ExecutionOptions executionOptions = Executor.ExecutionOptions.AddOutputter;

                    Token[] tokens;
                    ParseError[] errors;

                    // Detect if they're using input. If so, read from it.
                    Ast parsedInput = Parser.ParseFile(filePath, out tokens, out errors);
                    if (AstSearcher.IsUsingDollarInput(parsedInput))
                    {
                        executionOptions |= Executor.ExecutionOptions.ReadInputObjects;

                        // We will consume all of the input to pass to the script, so don't try to read commands from stdin.
                        ui.ReadFromStdin = false;
                    }

                    exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, executionOptions);
                }
                else
                {
                    exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter);
                }

                // Pipeline.Invoke has thrown, that's bad. It means the script did not actually
                // execute properly. These exceptions should be reflected in the exit code
                if (e1 != null)
                {
                    if (!_noExit)
                    {
                        // Set ExitCode to 0x1
                        lock (hostGlobalLock)
                        {
                            _setShouldExitCalled = true;
                            _exitCodeFromRunspace = 0x1;
                            ShouldEndSession = true;
                        }
                    }

                    ReportException(e1, exec);
                }
            }
            else if (!String.IsNullOrEmpty(initialCommand))
            {
                // Run the command passed on the command line

                s_tracer.WriteLine("running initial command");

                Pipeline tempPipeline = exec.CreatePipeline(initialCommand, true);

                if (initialCommandArgs != null)
                {
                    // add the args passed to the command.

                    foreach (CommandParameter p in initialCommandArgs)
                    {
                        tempPipeline.Commands[0].Parameters.Add(p);
                    }
                }

                Exception e1;

                if (IsRunningAsync)
                {
                    Executor.ExecutionOptions executionOptions = Executor.ExecutionOptions.AddOutputter;

                    Token[] tokens;
                    ParseError[] errors;

                    // Detect if they're using input. If so, read from it.
                    Ast parsedInput = Parser.ParseInput(initialCommand, out tokens, out errors);
                    if (AstSearcher.IsUsingDollarInput(parsedInput))
                    {
                        executionOptions |= Executor.ExecutionOptions.ReadInputObjects;

                        // We will consume all of the input to pass to the script, so don't try to read commands from stdin.
                        ui.ReadFromStdin = false;
                    }

                    exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, executionOptions);
                }
                else
                {
                    exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter);
                }

                if (e1 != null)
                {
                    // Remember last exception
                    _lastRunspaceInitializationException = e1;
                    ReportException(e1, exec);
                }
            }
        }
Ejemplo n.º 17
0
		private int DoRunspaceLoop(string initialCommand, bool skipProfiles, Collection<CommandParameter> initialCommandArgs, bool staMode, bool importSystemModules, bool showInitialPrompt)
		{
			bool valueOrDefault;
			this.ExitCode = 0;
			while (!this.ShouldEndSession)
			{
				this.promptDisplayedInNativeCode = showInitialPrompt;
				this.runspaceOpenedWaitHandle = new ManualResetEvent(false);
				RunspaceCreationEventArgs runspaceCreationEventArg = new RunspaceCreationEventArgs(initialCommand, skipProfiles, staMode, importSystemModules, initialCommandArgs);
				ThreadPool.QueueUserWorkItem(new WaitCallback(this.CreateRunspace), runspaceCreationEventArg);
				if (this.noExit || this.ui.ReadFromStdin)
				{
					this.EnterNestedPrompt();
				}
				else
				{
					this.ShouldEndSession = true;
				}
				this.runspaceOpenedWaitHandle.WaitOne();
				if (this.ExitCode == -65536)
				{
					break;
				}
				if (!this.setShouldExitCalled)
				{
					Executor executor = new Executor(this, false, false);
					bool? nullable = executor.ExecuteCommandAndGetResultAsBool("$global:?");
					if (nullable.HasValue)
					{
						valueOrDefault = nullable.GetValueOrDefault();
					}
					else
					{
						valueOrDefault = false;
					}
					bool flag = valueOrDefault;
					if (!flag)
					{
						this.ExitCode = 1;
					}
					else
					{
						this.ExitCode = 0;
					}
				}
				else
				{
					this.ExitCode = this.exitCodeFromRunspace;
				}
				this.runspaceRef.Runspace.Close();
				this.runspaceRef = null;
				if (!staMode)
				{
					continue;
				}
				this.ShouldEndSession = true;
			}
			return this.ExitCode;
		}
Ejemplo n.º 18
0
        // NTRAID#Windows Out Of Band Releases-915506-2005/09/09
        // Removed HandleUnexpectedExceptions infrastructure
        private void ReportException(Exception e, Executor exec)
        {
            Dbg.Assert(e != null, "must supply an Exception");
            Dbg.Assert(exec != null, "must supply an Executor");

            // NTRAID#Windows Out Of Band Releases-915506-2005/09/09
            // Removed HandleUnexpectedExceptions infrastructure

            // Attempt to write the exception into the error stream so that the normal F&O machinery will 
            // display it according to preferences.

            object error = null;
            Pipeline tempPipeline = exec.CreatePipeline();

            // NTRAID#Windows OS Bugs-1143621-2005/04/08-sburns 

            IContainsErrorRecord icer = e as IContainsErrorRecord;

            if (icer != null)
            {
                error = icer.ErrorRecord;
            }
            else
            {
                error = (object)new ErrorRecord(e, "ConsoleHost.ReportException", ErrorCategory.NotSpecified, null);
            }

            PSObject wrappedError = new PSObject(error);
            PSNoteProperty note = new PSNoteProperty("writeErrorStream", true);
            wrappedError.Properties.Add(note);

            Exception e1 = null;

            tempPipeline.Input.Write(wrappedError);
            if (IsRunningAsync)
            {
                exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter);
            }
            else
            {
                exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter);
            }

            if (e1 != null)
            {
                // that didn't work.  Write out the error ourselves as a last resort.

                ReportExceptionFallback(e, null);
            }
        }
Ejemplo n.º 19
0
		internal Collection<PSObject> ExecuteCommand(string command, out Exception exceptionThrown, Executor.ExecutionOptions options)
		{
			Pipeline pipeline = this.CreatePipeline(command, (options & Executor.ExecutionOptions.AddToHistory) > Executor.ExecutionOptions.None);
			return this.ExecuteCommandHelper(pipeline, out exceptionThrown, options);
		}
Ejemplo n.º 20
0
        /// <summary>
        /// 
        /// Reads a line, and completes the input for the user if they hit tab.
        /// 
        /// </summary>
        /// <param name="exec">
        /// 
        /// The Executor instance on which to run any pipelines that are needed to find matches
        /// 
        /// </param>
        /// 
        /// <returns>
        /// 
        /// null on a break event
        /// the completed line otherwise
        /// 
        /// </returns>
        internal string ReadLineWithTabCompletion(Executor exec)
        {
            string input = null;
            string lastInput = "";

            ReadLineResult rlResult = ReadLineResult.endedOnEnter;

#if !UNIX
            ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle();

            string lastCompletion = "";
            Size screenBufferSize = RawUI.BufferSize;

            // Save the cursor position at the end of the prompt string so that we can restore it later to write the
            // completed input.

            Coordinates endOfPromptCursorPos = RawUI.CursorPosition;

            CommandCompletion commandCompletion = null;
            string completionInput = null;
#endif

            do
            {
                if (TryInvokeUserDefinedReadLine(out input))
                {
                    break;
                }

                input = ReadLine(true, lastInput, out rlResult, false, false);

                if (input == null)
                {
                    break;
                }

                if (rlResult == ReadLineResult.endedOnEnter)
                {
                    break;
                }

#if UNIX // Portable code only ends on enter (or no input), so tab is not processed
                throw new PlatformNotSupportedException("This readline state is unsupported in portable code!");
#else

                Coordinates endOfInputCursorPos = RawUI.CursorPosition;
                string completedInput = null;

                if (rlResult == ReadLineResult.endedOnTab || rlResult == ReadLineResult.endedOnShiftTab)
                {
                    int tabIndex = input.IndexOf(Tab, StringComparison.CurrentCulture);
                    Dbg.Assert(tabIndex != -1, "tab should appear in the input");

                    string restOfLine = string.Empty;
                    int leftover = input.Length - tabIndex - 1;
                    if (leftover > 0)
                    {
                        // We are reading from the console (not redirected, b/c we don't end on tab when redirected)
                        // If the cursor is at the end of a line, there is actually a space character at the cursor's position and when we type tab
                        // at the end of a line, that space character is replaced by the tab. But when we type tab at the middle of a line, the space
                        // character at the end is preserved, we should remove that space character because it's not provided by the user.
                        input = input.Remove(input.Length - 1);
                        restOfLine = input.Substring(tabIndex + 1);
                    }
                    input = input.Remove(tabIndex);

                    if (input != lastCompletion || commandCompletion == null)
                    {
                        completionInput = input;
                        commandCompletion = GetNewCompletionResults(input);
                    }

                    var completionResult = commandCompletion.GetNextResult(rlResult == ReadLineResult.endedOnTab);
                    if (completionResult != null)
                    {
                        completedInput = completionInput.Substring(0, commandCompletion.ReplacementIndex)
                                         + completionResult.CompletionText;
                    }
                    else
                    {
                        completedInput = completionInput;
                    }

                    if (restOfLine != string.Empty)
                    {
                        completedInput += restOfLine;
                    }

                    if (completedInput.Length > (maxInputLineLength - 2))
                    {
                        completedInput = completedInput.Substring(0, maxInputLineLength - 2);
                    }

                    // Remove any nulls from the string...
                    completedInput = RemoveNulls(completedInput);

                    // adjust the saved cursor position if the buffer scrolled as the user was typing (i.e. the user 
                    // typed past the end of the buffer).

                    int linesOfInput = (endOfPromptCursorPos.X + input.Length) / screenBufferSize.Width;
                    endOfPromptCursorPos.Y = endOfInputCursorPos.Y - linesOfInput;

                    // replace the displayed input with the new input
                    try
                    {
                        RawUI.CursorPosition = endOfPromptCursorPos;
                    }
                    catch (PSArgumentOutOfRangeException)
                    {
                        // If we go a range exception, it's because
                        // there's no room in the buffer for the completed
                        // line so we'll just pretend that there was no match...
                        break;
                    }

                    // When the string is written to the console, a space character is actually appended to the string
                    // and the cursor will flash at the position of that space character.
                    WriteToConsole(completedInput, false);

                    Coordinates endOfCompletionCursorPos = RawUI.CursorPosition;

                    // adjust the starting cursor position if the screen buffer has scrolled as a result of writing the 
                    // completed input (i.e. writing the completed input ran past the end of the buffer).

                    int linesOfCompletedInput = (endOfPromptCursorPos.X + completedInput.Length) / screenBufferSize.Width;
                    endOfPromptCursorPos.Y = endOfCompletionCursorPos.Y - linesOfCompletedInput;

                    // blank out any "leftover" old input.  That's everything between the cursor position at the time 
                    // the user hit tab up to the current cursor position after writing the completed text.

                    int deltaInput =
                        (endOfInputCursorPos.Y * screenBufferSize.Width + endOfInputCursorPos.X)
                        - (endOfCompletionCursorPos.Y * screenBufferSize.Width + endOfCompletionCursorPos.X);

                    if (deltaInput > 0)
                    {
                        ConsoleControl.FillConsoleOutputCharacter(handle, ' ', deltaInput, endOfCompletionCursorPos);
                    }

                    if (restOfLine != string.Empty)
                    {
                        lastCompletion = completedInput.Remove(completedInput.Length - restOfLine.Length);
                        SendLeftArrows(restOfLine.Length);
                    }
                    else
                    {
                        lastCompletion = completedInput;
                    }

                    lastInput = completedInput;
                }
#endif
            }
            while (true);

            // Since we did not transcribe any call to ReadLine, transcribe the results here.

            if (_parent.IsTranscribing)
            {
                // Reads always terminate with the enter key, so add that.

                _parent.WriteToTranscript(input + Crlf);
            }

            return input;
        }
Ejemplo n.º 21
0
		internal string ReadLineWithTabCompletion(Executor exec, bool useUserDefinedCustomReadLine)
		{
			string str;
			bool flag;
			SafeFileHandle activeScreenBufferHandle = ConsoleControl.GetActiveScreenBufferHandle();
			string str1 = null;
			string str2 = "";
			string str3 = "";
			ConsoleHostUserInterface.ReadLineResult readLineResult = ConsoleHostUserInterface.ReadLineResult.endedOnEnter;
			Size bufferSize = this.RawUI.BufferSize;
			Coordinates cursorPosition = this.RawUI.CursorPosition;
			CommandCompletion newCompletionResults = null;
			string str4 = null;
			while (!this.TryInvokeUserDefinedReadLine(out str1, useUserDefinedCustomReadLine))
			{
				str2 = "";
				str1 = this.ReadLine(true, str2, out readLineResult, false, false);
				Coordinates coordinate = this.RawUI.CursorPosition;
				if (str1 == null || readLineResult == ConsoleHostUserInterface.ReadLineResult.endedOnEnter)
				{
					break;
				}
				if (readLineResult != ConsoleHostUserInterface.ReadLineResult.endedOnTab && readLineResult != ConsoleHostUserInterface.ReadLineResult.endedOnShiftTab)
				{
					continue;
				}
				int num = str1.IndexOf("\t", StringComparison.CurrentCulture);
				string empty = string.Empty;
				int length = str1.Length - num - 1;
				if (length > 0)
				{
					if (!this.parent.IsStandardInputRedirected)
					{
						flag = false;
					}
					else
					{
						flag = this.readFromStdin;
					}
					bool flag1 = flag;
					if (!flag1)
					{
						str1 = str1.Remove(str1.Length - 1);
					}
					empty = str1.Substring(num + 1);
				}
				str1 = str1.Remove(num);
				if (str1 != str3 || newCompletionResults == null)
				{
					str4 = str1;
					newCompletionResults = this.GetNewCompletionResults(str1);
				}
				CompletionResult nextResult = newCompletionResults.GetNextResult(readLineResult == ConsoleHostUserInterface.ReadLineResult.endedOnTab);
				if (nextResult == null)
				{
					str = str4;
				}
				else
				{
					str = string.Concat(str4.Substring(0, newCompletionResults.ReplacementIndex), nextResult.CompletionText);
				}
				if (empty != string.Empty)
				{
					str = string.Concat(str, empty);
				}
				if (str.Length > 0x1ffe)
				{
					str = str.Substring(0, 0x1ffe);
				}
				str = this.RemoveNulls(str);
				int x = (cursorPosition.X + str1.Length) / bufferSize.Width;
				cursorPosition.Y = coordinate.Y - x;
				try
				{
					this.RawUI.CursorPosition = cursorPosition;
				}
				catch (PSArgumentOutOfRangeException pSArgumentOutOfRangeException)
				{
					break;
				}
				ConsoleControl.NativeMethods.Editor.Initial = str;
				//this.WriteToConsole(str, false);
				Coordinates cursorPosition1 = this.RawUI.CursorPosition;
				int x1 = (cursorPosition.X + str.Length) / bufferSize.Width;
				cursorPosition.Y = cursorPosition1.Y - x1;
				int y = coordinate.Y * bufferSize.Width + coordinate.X - cursorPosition1.Y * bufferSize.Width + cursorPosition1.X;
				if (y > 0)
				{
					ConsoleControl.FillConsoleOutputCharacter(activeScreenBufferHandle, ' ', y, cursorPosition1);
				}
				if (empty == string.Empty)
				{
					str3 = str;
				}
				else
				{
					str3 = str.Remove(str.Length - empty.Length);
					this.SendLeftArrows(empty.Length);
				}
				str2 = str;
			}
			if (this.parent.IsTranscribing)
			{
				this.parent.WriteToTranscript(string.Concat(str1, "\r\n"));
			}
			return str1;
		}