Esempio n. 1
0
        /// <summary>
        /// 
        /// Opens and Initializes the Host's sole Runspace.  Processes the startup scripts and runs any command passed on the
        /// command line.
        /// 
        /// </summary>

        //private void CreateRunspace(string initialCommand, bool skipProfiles, bool staMode, Collection<CommandParameter> initialCommandArgs)
        private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool staMode, bool importSystemModules, string configurationName, Collection<CommandParameter> initialCommandArgs)
        {
            Dbg.Assert(_runspaceRef == null, "runspace should be null");
#if !DEBUG
            Dbg.Assert(_configuration != null, "configuration should be set");
#endif

            s_runspaceInitTracer.WriteLine("Calling RunspaceFactory.CreateRunspace");

            try
            {
                Runspace consoleRunspace = null;
                bool psReadlineFailed = false;

                // Use InitialSessionState if available.
                if (DefaultInitialSessionState != null)
                {
                    // Load PSReadline by default unless there is no use:
                    //    - we're running a command/file and just exiting
                    //    - stdin is redirected by a parent process
                    //    - we're not interactive
                    //    - we're explicitly reading from stdin (the '-' argument)
                    // It's also important to have a scenario where PSReadline is not loaded so it can be updated, e.g.
                    //    powershell -command "Update-Module PSReadline"
                    // This should work just fine as long as no other instances of PowerShell are running.
                    ReadOnlyCollection<Microsoft.PowerShell.Commands.ModuleSpecification> defaultImportModulesList = null;
                    if (LoadPSReadline())
                    {
                        // Create and open Runspace with PSReadline.
                        defaultImportModulesList = DefaultInitialSessionState.Modules;
                        DefaultInitialSessionState.ImportPSModule(new[] { "PSReadLine" });
                        consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState);
                        try
                        {
                            OpenConsoleRunspace(consoleRunspace, staMode);
                        }
                        catch (Exception e)
                        {
                            CommandProcessorBase.CheckForSevereException(e);
                            consoleRunspace = null;
                            psReadlineFailed = true;
                        }
                    }

                    if (consoleRunspace == null)
                    {
                        if (psReadlineFailed)
                        {
                            // Try again but without importing the PSReadline module.
                            DefaultInitialSessionState.ClearPSModules();
                            DefaultInitialSessionState.ImportPSModule(defaultImportModulesList);
                        }
                        consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState);
                        OpenConsoleRunspace(consoleRunspace, staMode);
                    }
                }
                else
                {
                    consoleRunspace = RunspaceFactory.CreateRunspace(this, _configuration);
                    OpenConsoleRunspace(consoleRunspace, staMode);
                }

                _runspaceRef = new RunspaceRef(consoleRunspace);

                if (psReadlineFailed)
                {
                    // Notify the user that PSReadline could not be loaded.
                    Console.Error.WriteLine(ConsoleHostStrings.CannotLoadPSReadline);
                }
            }
            catch (Exception e)
            {
                // no need to do CheckForSevereException here
                // since the ConsoleHostStartupException is uncaught 
                // higher in the call stack and the whole process
                // will exit soon
                throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStarted, e);
            }
            finally
            {
                // Stop PerfTrack
                PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStop, PSOpcode.WinStop,
                                                   PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational);
            }

            // Record how long it took from process start to runspace open for telemetry.
            _readyForInputTimeInMS = (DateTime.Now - Process.GetCurrentProcess().StartTime).TotalMilliseconds;

            DoRunspaceInitialization(importSystemModules, skipProfiles, initialCommand, configurationName, initialCommandArgs);
        }
Esempio n. 2
0
		public void SetRunspace (Runspace runspace)
		{
			_runspace = runspace;
			RunspaceRef = new System.Management.Automation.Remoting.RunspaceRef(_runspace);
		}
Esempio n. 3
0
		private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool staMode, bool importSystemModules, Collection<CommandParameter> initialCommandArgs)
		{
			ConsoleHost.runspaceInitTracer.WriteLine("Calling RunspaceFactory.CreateRunspace", new object[0]);
			if (ConsoleHost.DefaultInitialSessionState == null)
			{
				this.configuration.ImportSystemModules = importSystemModules;
				this.runspaceRef = new RunspaceRef(RunspaceFactory.CreateRunspace(this, this.configuration));
			}
			else
			{
				this.runspaceRef = new RunspaceRef(RunspaceFactory.CreateRunspace(this, ConsoleHost.DefaultInitialSessionState));
			}
			if (staMode)
			{
				this.runspaceRef.Runspace.ApartmentState = ApartmentState.STA;
				this.runspaceRef.Runspace.ThreadOptions = PSThreadOptions.ReuseThread;
			}
			this.runspaceRef.Runspace.EngineActivityId = EtwActivity.GetActivityId();
			ConsoleHost.runspaceInitTracer.WriteLine("Calling Runspace.Open", new object[0]);
			try
			{
				try
				{
					this.runspaceRef.Runspace.Open();
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					throw new ConsoleHost.ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStarted, exception);
				}
			}
			finally
			{
				PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStop, PSOpcode.WinStop, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational, new object[0]);
			}
			this.runspaceIsReady = true;
			this.DoRunspaceInitialization(importSystemModules, skipProfiles, initialCommand, initialCommandArgs);
			this.runspaceOpenedWaitHandle.Set();
		}
Esempio n. 4
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;
		}
Esempio n. 5
0
		private void Dispose(bool isDisposingNotFinalizing)
		{
			if (!this.isDisposed)
			{
				if (isDisposingNotFinalizing)
				{
					if (this.IsTranscribing)
					{
						this.StopTranscribing();
					}
					if (this.outputSerializer != null)
					{
						this.outputSerializer.End();
					}
					if (this.errorSerializer != null)
					{
						this.errorSerializer.End();
					}
					if (this.runspaceRef != null)
					{
						try
						{
							this.runspaceRef.Runspace.Dispose();
						}
						catch (InvalidRunspaceStateException invalidRunspaceStateException)
						{
						}
					}
					this.runspaceRef = null;
					this.hostGlobalLock = null;
					this.ui = null;
					if (this.runspaceOpenedWaitHandle != null)
					{
						this.runspaceOpenedWaitHandle.Close();
						this.runspaceOpenedWaitHandle = null;
					}
				}
				ConsoleControl.RemoveBreakHandler();
			 	if (this.breakHandlerGcHandle.IsAllocated) this.breakHandlerGcHandle.Free();
			}
			this.isDisposed = true;
		}