Example #1
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);
                }
            }
        }
Example #2
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;
				}
			}
		}