private void Start(bool incomingStream) { if (this.disposed) { throw PSTraceSource.NewObjectDisposedException("PipelineProcessor"); } if (this.Stopping) { throw new PipelineStoppedException(); } if (!this.executionStarted) { if ((this._commands == null) || (this._commands.Count == 0)) { throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "PipelineExecuteRequiresAtLeastOneCommand", new object[0]); } CommandProcessorBase base2 = this._commands[0]; if ((base2 == null) || (base2.CommandRuntime == null)) { throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "PipelineExecuteRequiresAtLeastOneCommand", new object[0]); } if (this.executionScope == null) { this.executionScope = base2.Context.EngineSessionState.CurrentScope; } CommandProcessorBase base3 = this._commands[this._commands.Count - 1]; if ((base3 == null) || (base3.CommandRuntime == null)) { throw PSTraceSource.NewInvalidOperationException(); } if (this.ExternalSuccessOutput != null) { base3.CommandRuntime.OutputPipe.ExternalWriter = this.ExternalSuccessOutput; } this.SetExternalErrorOutput(); if ((this.ExternalInput == null) && !incomingStream) { base2.CommandRuntime.IsClosed = true; } IDictionary variableValue = base2.Context.GetVariableValue(SpecialVariables.PSDefaultParameterValuesVarPath, false) as IDictionary; this.executionStarted = true; int[] numArray = new int[this._commands.Count + 1]; for (int i = 0; i < this._commands.Count; i++) { CommandProcessorBase base4 = this._commands[i]; if (base4 == null) { throw PSTraceSource.NewInvalidOperationException(); } Guid engineActivityId = base4.Context.CurrentRunspace.EngineActivityId; Guid activityId = EtwActivity.CreateActivityId(); EtwActivity.SetActivityId(activityId); base4.PipelineActivityId = activityId; MshLog.LogCommandLifecycleEvent(base4.Context, CommandState.Started, base4.Command.MyInvocation); InvocationInfo myInvocation = base4.Command.MyInvocation; myInvocation.PipelinePosition = i + 1; myInvocation.PipelineLength = this._commands.Count; myInvocation.PipelineIterationInfo = numArray; base4.DoPrepare(variableValue); myInvocation.ExpectingInput = base4.IsPipelineInputExpected(); } this.SetupOutErrorVariable(); for (int j = 0; j < this._commands.Count; j++) { this._commands[j].DoBegin(); } } }
/// <summary> /// Starts managed MSH /// </summary> /// <param name="consoleFilePath"> /// Deprecated: Console file used to create a runspace configuration to start MSH /// </param> /// <param name="args"> /// Command line arguments to the managed MSH /// </param> #pragma warning disable 1573 public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)] string[] args, int argc) #pragma warning restore 1573 { System.Management.Automation.Runspaces.EarlyStartup.Init(); // Set ETW activity Id Guid activityId = EtwActivity.GetActivityId(); if (activityId == Guid.Empty) { EtwActivity.SetActivityId(EtwActivity.CreateActivityId()); } PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational); // Windows Vista and later support non-traditional UI fallback ie., a // user on an Arabic machine can choose either French or English(US) as // UI fallback language. // CLR does not support this (non-traditional) fallback mechanism. // The currentUICulture returned NativeCultureResolver supports this non // traditional fallback on Vista. So it is important to set currentUICulture // in the beginning before we do anything. Thread.CurrentThread.CurrentUICulture = NativeCultureResolver.UICulture; Thread.CurrentThread.CurrentCulture = NativeCultureResolver.Culture; #if DEBUG if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Attach the debugger to continue..."); while (!System.Diagnostics.Debugger.IsAttached) { Thread.Sleep(100); } System.Diagnostics.Debugger.Break(); } #endif ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); int exitCode = 0; try { var banner = ManagedEntranceStrings.ShellBannerNonWindowsPowerShell; var formattedBanner = string.Format(CultureInfo.InvariantCulture, banner, PSVersionInfo.GitCommitId); exitCode = Microsoft.PowerShell.ConsoleShell.Start( formattedBanner, ManagedEntranceStrings.UsageHelp, args); } catch (System.Management.Automation.Host.HostException e) { if (e.InnerException != null && e.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception)) { System.ComponentModel.Win32Exception win32e = e.InnerException as System.ComponentModel.Win32Exception; // These exceptions are caused by killing conhost.exe // 1236, network connection aborted by local system // 0x6, invalid console handle if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236) { return(exitCode); } } System.Environment.FailFast(e.Message, e); } catch (Exception e) { System.Environment.FailFast(e.Message, e); } return(exitCode); }
#pragma warning restore 1573 #else public int Start(string consoleFilePath, string[] args) #endif { #if !CORECLR // For long-path support, Full .NET requires some AppContext switches; // (for CoreCLR this is Not needed, because CoreCLR supports long paths by default) // internally in .NET they are cached once retrieved and are typically hit very early during an application run; // so per .NET team's recommendation, we are setting them as soon as we enter managed code. EnableLongPathsInDotNetIfAvailable(); #endif System.Management.Automation.Runspaces.EarlyStartup.Init(); // Set ETW activity Id Guid activityId = EtwActivity.GetActivityId(); if (activityId == Guid.Empty) { EtwActivity.SetActivityId(EtwActivity.CreateActivityId()); } PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational); #if !CORECLR // Register crash reports in non-server mode WindowsErrorReporting.RegisterWindowsErrorReporting(false); #endif try { // Windows Vista and later support non-traditional UI fallback ie., a // user on an Arabic machine can choose either French or English(US) as // UI fallback language. // CLR does not support this (non-traditional) fallback mechanism. // The currentUICulture returned NativeCultureResolver supports this non // traditional fallback on Vista. So it is important to set currentUICulture // in the beginning before we do anything. ClrFacade.SetCurrentThreadUiCulture(NativeCultureResolver.UICulture); ClrFacade.SetCurrentThreadCulture(NativeCultureResolver.Culture); RunspaceConfigForSingleShell configuration = null; PSConsoleLoadException warning = null; // PSSnapInException will cause the control to return back to the native code // and stuff the EXCEPINFO field with the message of the exception. // The native code will print this out and exit the process. if (string.IsNullOrEmpty(consoleFilePath)) { #if DEBUG // Special switches for debug mode to allow self-hosting on InitialSessionState instead // of runspace configuration... if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-iss", StringComparison.OrdinalIgnoreCase)) { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } else if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Attach the debugger and hit enter to continue:"); Console.ReadLine(); ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } else { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } #else ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; #endif } else { //TODO : Deprecate RunspaceConfiguration and use InitialSessionState configuration = RunspaceConfigForSingleShell.Create(consoleFilePath, out warning); } int exitCode = 0; try { #if CORECLR var banner = ManagedEntranceStrings.ShellBannerNonWindowsPowerShell; #else var banner = ManagedEntranceStrings.ShellBanner; #endif exitCode = Microsoft.PowerShell.ConsoleShell.Start( configuration, banner, ManagedEntranceStrings.ShellHelp, warning == null ? null : warning.Message, args); } catch (System.Management.Automation.Host.HostException e) { if (e.InnerException != null && e.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception)) { System.ComponentModel.Win32Exception win32e = e.InnerException as System.ComponentModel.Win32Exception; // These exceptions are caused by killing conhost.exe // 1236, network connection aborted by local system // 0x6, invalid console handle if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236) { return(exitCode); } } #if CORECLR System.Environment.FailFast(e.Message); #else WindowsErrorReporting.FailFast(e); #endif } catch (Exception e) { #if CORECLR System.Management.Automation.Environment.FailFast(e.Message); #else // exceptions caught here should cause Watson. // Must call FailFast; otherwise the exception will be returned to the native code // which will just print out the exception message without Watson WindowsErrorReporting.FailFast(e); #endif } return(exitCode); } finally { #if !CORECLR WindowsErrorReporting.WaitForPendingReports(); #endif } }
private void InvokeHelper() { PipelineProcessor item = null; try { base.RaisePipelineStateEvents(); this.RecordPipelineStartTime(); try { item = this.CreatePipelineProcessor(); } catch (Exception exception) { if (base.SetPipelineSessionState) { base.SetHadErrors(true); this.Runspace.ExecutionContext.AppendDollarError(exception); } throw; } if (this.useExternalInput) { item.ExternalInput = base.InputStream.ObjectReader; } item.ExternalSuccessOutput = base.OutputStream.ObjectWriter; item.ExternalErrorOutput = base.ErrorStream.ObjectWriter; if (!this.IsChild) { this.LocalRunspace.ExecutionContext.InternalHost.InternalUI.SetInformationalMessageBuffers(base.InformationalBuffers); } bool questionMarkVariableValue = true; bool exceptionHandlerInEnclosingStatementBlock = this.LocalRunspace.ExecutionContext.ExceptionHandlerInEnclosingStatementBlock; this.LocalRunspace.ExecutionContext.ExceptionHandlerInEnclosingStatementBlock = false; try { this._stopper.Push(item); if (!base.AddToHistory) { questionMarkVariableValue = this.LocalRunspace.ExecutionContext.QuestionMarkVariableValue; this.LocalRunspace.ExecutionContext.IgnoreScriptDebug = true; } else { this.LocalRunspace.ExecutionContext.IgnoreScriptDebug = false; } if (!this.IsNested && !base.IsPulsePipeline) { this.LocalRunspace.ExecutionContext.ResetRedirection(); } try { item.Execute(); base.SetHadErrors(item.ExecutionFailed); } catch (ExitException exception2) { base.SetHadErrors(item.ExecutionFailed); int newValue = 1; if (this.IsNested) { try { newValue = (int)exception2.Argument; this.LocalRunspace.ExecutionContext.SetVariable(SpecialVariables.LastExitCodeVarPath, newValue); return; } finally { try { this.LocalRunspace.ExecutionContext.EngineHostInterface.ExitNestedPrompt(); } catch (ExitNestedPromptException) { } } } try { newValue = (int)exception2.Argument; } finally { this.LocalRunspace.ExecutionContext.EngineHostInterface.SetShouldExit(newValue); } } catch (ExitNestedPromptException) { } catch (FlowControlException) { } catch (Exception) { base.SetHadErrors(true); throw; } } finally { if ((item != null) && (item.Commands != null)) { for (int i = 0; i < item.Commands.Count; i++) { CommandProcessorBase base2 = item.Commands[i]; EtwActivity.SetActivityId(base2.PipelineActivityId); MshLog.LogCommandLifecycleEvent(base2.Context, CommandState.Terminated, base2.Command.MyInvocation); } } PSLocalEventManager events = this.LocalRunspace.Events as PSLocalEventManager; if (events != null) { events.ProcessPendingActions(); } this.LocalRunspace.ExecutionContext.ExceptionHandlerInEnclosingStatementBlock = exceptionHandlerInEnclosingStatementBlock; if (!this.IsChild) { this.LocalRunspace.ExecutionContext.InternalHost.InternalUI.SetInformationalMessageBuffers(null); } this._stopper.Pop(false); if (!base.AddToHistory) { this.LocalRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkVariableValue; } } } catch (FlowControlException) { } finally { if (item != null) { item.Dispose(); item = null; } } }
public int Start(string consoleFilePath, string[] args) { int num; string message; Guid activityId = EtwActivity.GetActivityId(); if (activityId == Guid.Empty) { EtwActivity.SetActivityId(EtwActivity.CreateActivityId()); } PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational, new object[0]); WindowsErrorReporting.RegisterWindowsErrorReporting(false); try { Thread.CurrentThread.CurrentUICulture = NativeCultureResolver.UICulture; Thread.CurrentThread.CurrentCulture = NativeCultureResolver.Culture; RunspaceConfigForSingleShell runspaceConfigForSingleShell = null; PSConsoleLoadException pSConsoleLoadException = null; if (!string.IsNullOrEmpty(consoleFilePath)) { runspaceConfigForSingleShell = RunspaceConfigForSingleShell.Create(consoleFilePath, out pSConsoleLoadException); } else { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); runspaceConfigForSingleShell = null; if (Process.GetCurrentProcess().MainWindowHandle != IntPtr.Zero) { ConsoleHost.DefaultInitialSessionState.WarmUpTabCompletionOnIdle = true; } } int num1 = 0; try { RunspaceConfigForSingleShell runspaceConfigForSingleShell1 = runspaceConfigForSingleShell; string shellBanner = ManagedEntranceStrings.ShellBanner; string shellHelp = ManagedEntranceStrings.ShellHelp; if (pSConsoleLoadException == null) { message = null; } else { message = pSConsoleLoadException.Message; } num1 = ConsoleShell.Start(runspaceConfigForSingleShell1, shellBanner, shellHelp, message, args); } catch (HostException hostException1) { HostException hostException = hostException1; if (hostException.InnerException != null && hostException.InnerException.GetType() == typeof(Win32Exception)) { Win32Exception innerException = hostException.InnerException as Win32Exception; if (innerException.NativeErrorCode == 6 || innerException.NativeErrorCode == 0x4d4) { num = num1; return(num); } } WindowsErrorReporting.FailFast(hostException); } catch (Exception exception1) { Exception exception = exception1; WindowsErrorReporting.FailFast(exception); } num = num1; } finally { WindowsErrorReporting.WaitForPendingReports(); } return(num); }
/// <summary> /// Starts managed MSH /// </summary> /// <param name="consoleFilePath"> /// Console file used to create a runspace configuration to start MSH /// </param> /// <param name="args"> /// Command line arguments to the managed MSH /// </param> #pragma warning disable 1573 public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)] string[] args, int argc) #pragma warning restore 1573 { System.Management.Automation.Runspaces.EarlyStartup.Init(); // Set ETW activity Id Guid activityId = EtwActivity.GetActivityId(); if (activityId == Guid.Empty) { EtwActivity.SetActivityId(EtwActivity.CreateActivityId()); } PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational); // Windows Vista and later support non-traditional UI fallback ie., a // user on an Arabic machine can choose either French or English(US) as // UI fallback language. // CLR does not support this (non-traditional) fallback mechanism. // The currentUICulture returned NativeCultureResolver supports this non // traditional fallback on Vista. So it is important to set currentUICulture // in the beginning before we do anything. Thread.CurrentThread.CurrentUICulture = NativeCultureResolver.UICulture; Thread.CurrentThread.CurrentCulture = NativeCultureResolver.Culture; RunspaceConfigForSingleShell configuration = null; PSConsoleLoadException warning = null; // PSSnapInException will cause the control to return back to the native code // and stuff the EXCEPINFO field with the message of the exception. // The native code will print this out and exit the process. if (string.IsNullOrEmpty(consoleFilePath)) { #if DEBUG // Special switches for debug mode to allow self-hosting on InitialSessionState instead // of runspace configuration... if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-iss", StringComparison.OrdinalIgnoreCase)) { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } else if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Attach the debugger and hit enter to continue:"); Console.ReadLine(); ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } else { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } #else ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; #endif } else { //TODO : Deprecate RunspaceConfiguration and use InitialSessionState configuration = RunspaceConfigForSingleShell.Create(consoleFilePath, out warning); } int exitCode = 0; try { var banner = ManagedEntranceStrings.ShellBannerNonWindowsPowerShell; var formattedBanner = string.Format(CultureInfo.InvariantCulture, banner, PSVersionInfo.GitCommitId); exitCode = Microsoft.PowerShell.ConsoleShell.Start( configuration, formattedBanner, ManagedEntranceStrings.ShellHelp, warning == null ? null : warning.Message, args); } catch (System.Management.Automation.Host.HostException e) { if (e.InnerException != null && e.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception)) { System.ComponentModel.Win32Exception win32e = e.InnerException as System.ComponentModel.Win32Exception; // These exceptions are caused by killing conhost.exe // 1236, network connection aborted by local system // 0x6, invalid console handle if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236) { return(exitCode); } } System.Environment.FailFast(e.Message, e); } catch (Exception e) { System.Environment.FailFast(e.Message, e); } return(exitCode); }