/// <summary> /// /// Constructs an instance /// /// </summary> /// <param name="parent"></param> /// <exception/> internal ConsoleHostUserInterface(ConsoleHost parent) { Dbg.Assert(parent != null, "parent may not be null"); _parent = parent; _rawui = new ConsoleHostRawUserInterface(this); #if UNIX SupportsVirtualTerminal = true; #else try { // Turn on virtual terminal if possible. // This might throw - not sure how exactly (no console), but if it does, we shouldn't fail to start. var handle = ConsoleControl.GetActiveScreenBufferHandle(); var m = ConsoleControl.GetMode(handle); if (ConsoleControl.NativeMethods.SetConsoleMode(handle.DangerousGetHandle(), (uint)(m | ConsoleControl.ConsoleModes.VirtualTerminal))) { // We only know if vt100 is supported if the previous call actually set the new flag, older // systems ignore the setting. m = ConsoleControl.GetMode(handle); this.SupportsVirtualTerminal = (m & ConsoleControl.ConsoleModes.VirtualTerminal) != 0; } } catch { } #endif _isInteractiveTestToolListening = false; }
internal Executor(ConsoleHost parent, bool useNestedPipelines, bool isPromptFunctionExecutor) { this.instanceStateLock = new object(); this.parent = parent; this.useNestedPipelines = useNestedPipelines; this.isPromptFunctionExecutor = isPromptFunctionExecutor; this.Reset(); }
/// <summary> /// /// Constructs a new instance /// /// </summary> /// <param name="parent"> /// /// A reference to the parent ConsoleHost that created this instance. /// /// </param> /// <param name="useNestedPipelines"> /// /// true if the executor is supposed to use nested pipelines; false if not. /// /// </param> /// <param name="isPromptFunctionExecutor"> /// /// True if the instance will be used to execute the prompt function, which will delay stopping the pipeline by some /// milliseconds. This we prevent us from stopping the pipeline so quickly that when the user leans on the ctrl-c key /// that the prompt "stops working" (because it is being stopped faster than it can run to completion). /// /// </param> internal Executor(ConsoleHost parent, bool useNestedPipelines, bool isPromptFunctionExecutor) { Dbg.Assert(parent != null, "parent should not be null"); _parent = parent; this.useNestedPipelines = useNestedPipelines; _isPromptFunctionExecutor = isPromptFunctionExecutor; Reset(); }
internal CommandLineParameterParser(ConsoleHost p, Version ver, string bannerText, string helpText) { Dbg.Assert(p != null, "parent ConsoleHost must be supplied"); _bannerText = bannerText; _helpText = helpText; _parent = p; _ui = (ConsoleHostUserInterface)p.UI; _ver = ver; }
/// <summary>Entry point in to ConsoleShell. Used to create a custom Powershell console application.</summary> /// <param name="initialSessionState">InitialSessionState to be used by the ConsoleHost.</param> /// <param name="bannerText">Banner text to be displayed by ConsoleHost.</param> /// <param name="helpText">Help text for the shell.</param> /// <param name="args">Commandline parameters specified by user.</param> /// <returns>An integer value which should be used as exit code for the process.</returns> public static int Start(InitialSessionState initialSessionState, string bannerText, string helpText, string[] args) { if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } if (args == null) { throw PSTraceSource.NewArgumentNullException(nameof(args)); } ConsoleHost.DefaultInitialSessionState = initialSessionState; return(ConsoleHost.Start(bannerText, helpText, args)); }
PostWrite(string value) { PostWrite(); if (_parent.IsTranscribing) { try { _parent.WriteToTranscript(value); } catch (Exception e) { ConsoleHost.CheckForSevereException(e); _parent.IsTranscribing = false; } } }
PostRead(string value) { PostRead(); if (_parent.IsTranscribing) { try { // Reads always terminate with the enter key, so add that. _parent.WriteToTranscript(value + Crlf); } catch (Exception e) { ConsoleHost.CheckForSevereException(e); _parent.IsTranscribing = false; } } }
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); } Executor currentExecutor = Executor.CurrentExecutor; Executor.CurrentExecutor = this; lock (this.instanceStateLock) { this.pipeline = tempPipeline; } try { try { pSObjects = tempPipeline.Invoke(); } catch (Exception exception1) { Exception exception = exception1; ConsoleHost.CheckForSevereException(exception); exceptionThrown = exception; } } finally { this.parent.ui.ResetProgress(); Executor.CurrentExecutor = currentExecutor; this.Reset(); } return(pSObjects); }
private static int StartImpl( InitialSessionState initialSessionState, string?bannerText, string?helpText, string[] args, bool issProvided) { if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } if (args == null) { throw PSTraceSource.NewArgumentNullException(nameof(args)); } ConsoleHost.ParseCommandLine(args); ConsoleHost.DefaultInitialSessionState = initialSessionState; return(ConsoleHost.Start(bannerText, helpText, issProvided)); }
Start(RunspaceConfiguration configuration, string bannerText, string helpText, string preStartWarning, string[] args) { if (args == null) { throw PSTraceSource.NewArgumentNullException("args"); } // The default font face used for Powershell Console is Lucida Console. // However certain CJK locales dont support Lucida Console font. Hence for such // locales the console font is updated to Raster dynamically. // For NanoServer: // 1. There is no GetCurrentConsoleFontEx / SetCurrentConsoleFontEx on NanoServer; // 2. We don't handle CJK locales on NanoServer due to lack of win32 API supports on NanoServer. #if !CORECLR ConsoleControl.UpdateLocaleSpecificFont(); #endif return(ConsoleHost.Start(configuration, bannerText, helpText, preStartWarning, args)); }
private void ParseHelper(string[] args) { Dbg.Assert(args != null, "Argument 'args' to ParseHelper should never be null"); bool noexitSeen = false; for (int i = 0; i < args.Length; ++i) { // Invariant culture used because command-line parameters are not localized. string switchKey = args[i].Trim().ToLowerInvariant(); if (String.IsNullOrEmpty(switchKey)) { continue; } if (!SpecialCharacters.IsDash(switchKey[0]) && switchKey[0] != '/') { // then its a command --i; ParseCommand(args, ref i, noexitSeen, false); break; } // chop off the first character so that we're agnostic wrt specifying / or - // in front of the switch name. switchKey = switchKey.Substring(1); // chop off the second dash so we're agnostic wrt specifying - or -- if (!String.IsNullOrEmpty(switchKey) && SpecialCharacters.IsDash(switchKey[0])) { switchKey = switchKey.Substring(1); } if (MatchSwitch(switchKey, "help", "h") || MatchSwitch(switchKey, "?", "?")) { _showHelp = true; _abortStartup = true; } else if (MatchSwitch(switchKey, "noexit", "noe")) { _noExit = true; noexitSeen = true; } else if (MatchSwitch(switchKey, "importsystemmodules", "imp")) { _importSystemModules = true; } else if (MatchSwitch(switchKey, "noprofile", "nop")) { _skipUserInit = true; } else if (MatchSwitch(switchKey, "nologo", "nol")) { _showBanner = false; } else if (MatchSwitch(switchKey, "noninteractive", "noni")) { _noInteractive = true; } else if (MatchSwitch(switchKey, "socketservermode", "so")) { _socketServerMode = true; } else if (MatchSwitch(switchKey, "servermode", "s")) { _serverMode = true; } else if (MatchSwitch(switchKey, "namedpipeservermode", "nam")) { _namedPipeServerMode = true; } else if (MatchSwitch(switchKey, "sshservermode", "sshs")) { _sshServerMode = true; } else if (MatchSwitch(switchKey, "configurationname", "config")) { ++i; if (i >= args.Length) { WriteCommandLineError( CommandLineParameterParserStrings.MissingConfigurationNameArgument); break; } _configurationName = args[i]; } else if (MatchSwitch(switchKey, "command", "c")) { if (!ParseCommand(args, ref i, noexitSeen, false)) { break; } } #if !CORECLR // windowstyle parameter not supported on NanoServer because ProcessWindowStyle does Not exist on CoreCLR else if (MatchSwitch(switchKey, "windowstyle", "w")) { ++i; if (i >= args.Length) { WriteCommandLineError( CommandLineParameterParserStrings.MissingWindowStyleArgument); break; } try { ProcessWindowStyle style = (ProcessWindowStyle)LanguagePrimitives.ConvertTo( args[i], typeof(ProcessWindowStyle), CultureInfo.InvariantCulture); ConsoleControl.SetConsoleMode(style); } catch (PSInvalidCastException e) { WriteCommandLineError( string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, args[i], e.Message)); break; } } #endif else if (MatchSwitch(switchKey, "file", "f")) { // Process file execution. We don't need to worry about checking -command // since if -command comes before -file, -file will be treated as part // of the script to evaluate. If -file comes before -command, it will // treat -command as an argument to the script... ++i; if (i >= args.Length) { WriteCommandLineError( CommandLineParameterParserStrings.MissingFileArgument, showHelp: true, showBanner: true); break; } // Don't show the startup banner unless -noexit has been specified. if (!noexitSeen) { _showBanner = false; } // Process interactive input... if (args[i] == "-") { // the arg to -file is -, which is secret code for "read the commands from stdin with prompts" _explicitReadCommandsFromStdin = true; _noPrompt = false; } else { // Exit on script completion unless -noexit was specified... if (!noexitSeen) { _noExit = false; } // We need to get the full path to the script because it will be // executed after the profiles are run and they may change the current // directory. string exceptionMessage = null; try { // Normalize slashes _file = args[i].Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); _file = Path.GetFullPath(_file); } catch (Exception e) { // Catch all exceptions - we're just going to exit anyway so there's // no issue of the system being destabilized. We'll still // Watson on "severe" exceptions to get the reports. ConsoleHost.CheckForSevereException(e); exceptionMessage = e.Message; } if (exceptionMessage != null) { WriteCommandLineError( string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgument, args[i], exceptionMessage), showBanner: true); break; } if (!Path.GetExtension(_file).Equals(".ps1", StringComparison.OrdinalIgnoreCase)) { WriteCommandLineError( string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgumentExtension, args[i]), showBanner: true); break; } if (!System.IO.File.Exists(_file)) { WriteCommandLineError( string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.ArgumentFileDoesNotExist, args[i]), showBanner: true); break; } i++; Regex argPattern = new Regex(@"^.\w+\:", RegexOptions.CultureInvariant); string pendingParameter = null; // Accumulate the arguments to this script... while (i < args.Length) { string arg = args[i]; // If there was a pending parameter, add a named parameter // using the pending parameter and current argument if (pendingParameter != null) { _collectedArgs.Add(new CommandParameter(pendingParameter, arg)); pendingParameter = null; } else if (!string.IsNullOrEmpty(arg) && SpecialCharacters.IsDash(arg[0])) { Match m = argPattern.Match(arg); if (m.Success) { int offset = arg.IndexOf(':'); if (offset == arg.Length - 1) { pendingParameter = arg.TrimEnd(':'); } else { _collectedArgs.Add(new CommandParameter(arg.Substring(0, offset), arg.Substring(offset + 1))); } } else { _collectedArgs.Add(new CommandParameter(arg)); } } else { _collectedArgs.Add(new CommandParameter(null, arg)); } ++i; } } break; } #if DEBUG // this option is useful when debugging ConsoleHost remotely using VS remote debugging, as you can only // attach to an already running process with that debugger. else if (MatchSwitch(switchKey, "wait", "w")) { // This does not need to be localized: its chk only _ui.WriteToConsole("Waiting - type enter to continue:", false); _ui.ReadLine(); } // this option is useful for testing the initial InitialSessionState experience else if (MatchSwitch(switchKey, "iss", "iss")) { // Just toss this option, it was processed earlier... } // this option is useful for testing the initial InitialSessionState experience // this is independent of the normal wait switch because configuration processing // happens so early in the cycle... else if (MatchSwitch(switchKey, "isswait", "isswait")) { // Just toss this option, it was processed earlier... } else if (MatchSwitch(switchKey, "modules", "mod")) { if (ConsoleHost.DefaultInitialSessionState == null) { WriteCommandLineError( "The -module option can only be specified with the -iss option.", showHelp: true, showBanner: true); break; } ++i; int moduleCount = 0; // Accumulate the arguments to this script... while (i < args.Length) { string arg = args[i]; if (!string.IsNullOrEmpty(arg) && SpecialCharacters.IsDash(arg[0])) { break; } else { ConsoleHost.DefaultInitialSessionState.ImportPSModule(new string[] { arg }); moduleCount++; } ++i; } if (moduleCount < 1) { _ui.WriteErrorLine("No modules specified for -module option"); } } #endif else if (MatchSwitch(switchKey, "outputformat", "o") || MatchSwitch(switchKey, "of", "o")) { ParseFormat(args, ref i, ref _outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter); } else if (MatchSwitch(switchKey, "inputformat", "i") || MatchSwitch(switchKey, "if", "i")) { ParseFormat(args, ref i, ref _inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter); } else if (MatchSwitch(switchKey, "executionpolicy", "ex") || MatchSwitch(switchKey, "ep", "ep")) { ParseExecutionPolicy(args, ref i, ref _executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter); } else if (MatchSwitch(switchKey, "encodedcommand", "e") || MatchSwitch(switchKey, "ec", "e")) { _wasCommandEncoded = true; if (!ParseCommand(args, ref i, noexitSeen, true)) { break; } } else if (MatchSwitch(switchKey, "encodedarguments", "encodeda") || MatchSwitch(switchKey, "ea", "ea")) { if (!CollectArgs(args, ref i)) { break; } } #if !CORECLR // explicit setting of the ApartmentState Not supported on NanoServer else if (MatchSwitch(switchKey, "sta", "s")) { if (_staMode.HasValue) { // -sta and -mta are mutually exclusive. WriteCommandLineError( CommandLineParameterParserStrings.MtaStaMutuallyExclusive); break; } _staMode = true; } // Win8: 182409 PowerShell 3.0 should run in STA mode by default..so, consequently adding the switch -mta. // Not deleting -sta for backward compatability reasons else if (MatchSwitch(switchKey, "mta", "mta")) { if (_staMode.HasValue) { // -sta and -mta are mutually exclusive. WriteCommandLineError( CommandLineParameterParserStrings.MtaStaMutuallyExclusive); break; } _staMode = false; } #endif else { // The first parameter we fail to recognize marks the beginning of the command string. --i; if (!ParseCommand(args, ref i, noexitSeen, false)) { break; } } } if (_showHelp) { ShowHelp(); } if (_showBanner && !_showHelp) { DisplayBanner(); } Dbg.Assert( ((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup) || (_exitCode == ConsoleHost.ExitCodeSuccess), "if exit code is failure, then abortstartup should be true"); }
/// <summary> /// Create single instance of ConsoleHost. /// </summary> internal static ConsoleHost CreateSingletonInstance(RunspaceConfiguration configuration) { Dbg.Assert(s_theConsoleHost == null, "CreateSingletonInstance should not be called multiple times"); s_theConsoleHost = new ConsoleHost(configuration); return s_theConsoleHost; }
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); }
internal static void RunNewInputLoop(ConsoleHost parent, bool isNested) { // creates an instance and adds it to the stack and starts it running. int stackCount = s_instanceStack.Count; if (stackCount == PSHost.MaximumNestedPromptLevel) { throw PSTraceSource.NewInvalidOperationException(ConsoleHostStrings.TooManyNestedPromptsError); } InputLoop il = new InputLoop(parent, isNested); s_instanceStack.Push(il); il.Run(s_instanceStack.Count > 1); // Once the loop has finished running, remove it from the instance stack. InputLoop il2 = s_instanceStack.Pop(); Dbg.Assert(il == il2, "top of instance stack does not correspond to the instance pushed"); }
internal CommandLineParameterParser(ConsoleHost p, Version ver, string bannerText, string helpText) { this.showBanner = true; this.staMode = null; this.noExit = true; this.collectedArgs = new Collection<CommandParameter>(); this.bannerText = bannerText; this.helpText = helpText; this.parent = p; this.ui = (ConsoleHostUserInterface)p.UI; this.ver = ver; }
internal static int Start(RunspaceConfiguration configuration, string bannerText, string helpText, string preStartWarning, string[] args) { int num = 0; Thread.CurrentThread.Name = "ConsoleHost main thread"; ConsoleHost.theConsoleHost = ConsoleHost.CreateSingletonInstance(configuration); ConsoleHost.theConsoleHost.BindBreakHandler(); PSHost.IsStdOutputRedirected = ConsoleHost.theConsoleHost.IsStandardOutputRedirected; if (args == null) { args = new string[0]; } if (!string.IsNullOrEmpty(preStartWarning)) { ConsoleHost.theConsoleHost.UI.WriteWarningLine(preStartWarning); } using (ConsoleHost.theConsoleHost) { ConsoleHost.cpp = new CommandLineParameterParser(ConsoleHost.theConsoleHost, ConsoleHost.theConsoleHost.ver, bannerText, helpText); string[] strArrays = new string[args.GetLength(0)]; args.CopyTo(strArrays, 0); ConsoleHost.cpp.Parse(strArrays); if (!ConsoleHost.cpp.ServerMode) { num = ConsoleHost.theConsoleHost.Run(ConsoleHost.cpp, !string.IsNullOrEmpty(preStartWarning)); } else { OutOfProcessMediator.Run(ConsoleHost.cpp.InitialCommand); num = 0; } } return num; }
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 waiterThereIsAFlyInMySoup = new PipelineFinishedWaitHandle(tempPipeline); 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(); waiterThereIsAFlyInMySoup.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) { ConsoleHost.CheckForSevereException(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(); } }
private void ParseHelper(string[] args) { bool flag = false; for (int i = 0; i < (int)args.Length; i++) { string lowerInvariant = args[i].Trim().ToLowerInvariant(); if (!string.IsNullOrEmpty(lowerInvariant)) { if (SpecialCharacters.IsDash(lowerInvariant[0]) || lowerInvariant[0] == '/') { lowerInvariant = lowerInvariant.Substring(1); if (this.MatchSwitch(lowerInvariant, "help", "h") || this.MatchSwitch(lowerInvariant, "?", "?")) { this.showHelp = true; this.abortStartup = true; } else { if (!this.MatchSwitch(lowerInvariant, "noexit", "noe")) { if (!this.MatchSwitch(lowerInvariant, "importsystemmodules", "imp")) { if (!this.MatchSwitch(lowerInvariant, "showinitialprompt", "show")) { if (!this.MatchSwitch(lowerInvariant, "noprofile", "nop")) { if (!this.MatchSwitch(lowerInvariant, "nologo", "nol")) { if (!this.MatchSwitch(lowerInvariant, "noninteractive", "noni")) { if (!this.MatchSwitch(lowerInvariant, "servermode", "s")) { if (!this.MatchSwitch(lowerInvariant, "command", "c")) { if (!this.MatchSwitch(lowerInvariant, "windowstyle", "w")) { if (!this.MatchSwitch(lowerInvariant, "file", "f")) { if (this.MatchSwitch(lowerInvariant, "outputformat", "o") || this.MatchSwitch(lowerInvariant, "of", "o")) { this.ParseFormat(args, ref i, ref this.outFormat, CommandLineParameterParserStrings.MissingOutputFormatParameter); } else { if (this.MatchSwitch(lowerInvariant, "inputformat", "i") || this.MatchSwitch(lowerInvariant, "if", "i")) { this.ParseFormat(args, ref i, ref this.inFormat, CommandLineParameterParserStrings.MissingInputFormatParameter); } else { if (this.MatchSwitch(lowerInvariant, "executionpolicy", "ex") || this.MatchSwitch(lowerInvariant, "ep", "ep")) { this.ParseExecutionPolicy(args, ref i, ref this.executionPolicy, CommandLineParameterParserStrings.MissingExecutionPolicyParameter); } else { if (this.MatchSwitch(lowerInvariant, "encodedcommand", "e") || this.MatchSwitch(lowerInvariant, "ec", "e")) { this.wasCommandEncoded = true; if (!this.ParseCommand(args, ref i, flag, true)) { break; } } else { if (this.MatchSwitch(lowerInvariant, "encodedarguments", "encodeda") || this.MatchSwitch(lowerInvariant, "ea", "ea")) { if (!this.CollectArgs(args, ref i)) { break; } } else { if (!this.MatchSwitch(lowerInvariant, "sta", "s")) { if (!this.MatchSwitch(lowerInvariant, "mta", "mta")) { i--; if (!this.ParseCommand(args, ref i, flag, false)) { break; } } else { if (!this.staMode.HasValue) { this.staMode = new bool?(false); } else { this.ui.WriteErrorLine(CommandLineParameterParserStrings.MtaStaMutuallyExclusive); this.showHelp = false; this.showBanner = false; this.abortStartup = true; this.exitCode = -196608; break; } } } else { if (!this.staMode.HasValue) { this.staMode = new bool?(true); } else { this.ui.WriteErrorLine(CommandLineParameterParserStrings.MtaStaMutuallyExclusive); this.showHelp = false; this.showBanner = false; this.abortStartup = true; this.exitCode = -196608; break; } } } } } } } } else { i++; if (i < (int)args.Length) { if (!flag) { this.showBanner = false; } if (!flag) { this.noExit = false; } if (args[i] != "-") { string message = null; try { this.file = Path.GetFullPath(args[i]); } catch (Exception exception1) { Exception exception = exception1; ConsoleHost.CheckForSevereException(exception); message = exception.Message; } if (message == null) { if (Path.GetExtension(this.file).Equals(".ps1", StringComparison.OrdinalIgnoreCase)) { if (System.IO.File.Exists(this.file)) { i++; Regex regex = new Regex("^.\\w+\\:", RegexOptions.CultureInvariant); string str = null; while (i < (int)args.Length) { string str1 = args[i]; if (str == null) { if (string.IsNullOrEmpty(str1) || !SpecialCharacters.IsDash(str1[0])) { this.collectedArgs.Add(new CommandParameter(null, str1)); } else { Match match = regex.Match(str1); if (!match.Success) { this.collectedArgs.Add(new CommandParameter(str1)); } else { int num = str1.IndexOf(':'); if (num != str1.Length - 1) { this.collectedArgs.Add(new CommandParameter(str1.Substring(0, num), str1.Substring(num + 1))); } else { char[] chrArray = new char[1]; chrArray[0] = ':'; str = str1.TrimEnd(chrArray); } } } } else { this.collectedArgs.Add(new CommandParameter(str, str1)); str = null; } i++; } break; } else { object[] objArray = new object[1]; objArray[0] = args[i]; this.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.ArgumentFileDoesNotExist, objArray)); this.showHelp = false; this.abortStartup = true; this.exitCode = -196608; break; } } else { object[] objArray1 = new object[1]; objArray1[0] = args[i]; this.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgumentExtension, objArray1)); this.showHelp = false; this.abortStartup = true; this.exitCode = -196608; break; } } else { object[] objArray2 = new object[2]; objArray2[0] = args[i]; objArray2[1] = message; this.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgument, objArray2)); this.showHelp = false; this.abortStartup = true; this.exitCode = -196608; break; } } else { this.readFromStdin = true; this.noPrompt = false; break; } } else { this.ui.WriteErrorLine(CommandLineParameterParserStrings.MissingFileArgument); this.showHelp = true; this.abortStartup = true; this.exitCode = -196608; break; } } } else { i++; if (i < (int)args.Length) { try { ProcessWindowStyle processWindowStyle = (ProcessWindowStyle)LanguagePrimitives.ConvertTo(args[i], typeof(ProcessWindowStyle), CultureInfo.InvariantCulture); ConsoleControl.SetConsoleMode(processWindowStyle); } catch (PSInvalidCastException pSInvalidCastException1) { PSInvalidCastException pSInvalidCastException = pSInvalidCastException1; object[] message1 = new object[2]; message1[0] = args[i]; message1[1] = pSInvalidCastException.Message; this.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, message1)); this.showHelp = false; this.showBanner = false; this.abortStartup = true; this.exitCode = -196608; break; } } else { this.ui.WriteErrorLine(CommandLineParameterParserStrings.MissingWindowStyleArgument); this.showHelp = false; this.showBanner = false; this.abortStartup = true; this.exitCode = -196608; break; } } } else { if (!this.ParseCommand(args, ref i, flag, false)) { break; } } } else { this.serverMode = true; } } else { this.noInteractive = true; if (ConsoleHost.DefaultInitialSessionState != null) { ConsoleHost.DefaultInitialSessionState.WarmUpTabCompletionOnIdle = false; } } } else { this.showBanner = false; } } else { this.skipUserInit = true; } } else { this.showInitialPrompt = true; } } else { this.importSystemModules = true; } } else { this.noExit = true; flag = true; } } } else { i--; this.ParseCommand(args, ref i, flag, false); break; } } } if (this.showHelp) { this.ShowHelp(); } if (this.showBanner && !this.showHelp) { this.ShowBanner(); } }
internal static ConsoleHost CreateSingletonInstance(RunspaceConfiguration configuration) { ConsoleHost.theConsoleHost = new ConsoleHost(configuration); return ConsoleHost.theConsoleHost; }
internal static void RunNewInputLoop(ConsoleHost parent, bool isNested) { int count = ConsoleHost.InputLoop.instanceStack.Count; if (count != 128) { ConsoleHost.InputLoop inputLoop = new ConsoleHost.InputLoop(parent, isNested); ConsoleHost.InputLoop.instanceStack.Push(inputLoop); inputLoop.Run(ConsoleHost.InputLoop.instanceStack.Count > 1); ConsoleHost.InputLoop.instanceStack.Pop(); return; } else { throw PSTraceSource.NewInvalidOperationException("ConsoleHostStrings", "TooManyNestedPromptsError", new object[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); }
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(); } }
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) { ConsoleHost.CheckForSevereException(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); }
private bool IsStandardHandleRedirected(long handleId, ref bool isHandleRedirectionDetermined, ref bool isHandleRedirected, ConsoleHost.InitializeStandardHandleDelegate handleInit) { lock (this.hostGlobalLock) { if (!isHandleRedirectionDetermined) { isHandleRedirected = false; IntPtr stdHandle = ConsoleControl.GetStdHandle(handleId); int num = 0; bool consoleMode = ConsoleControl.NativeMethods.GetConsoleMode(stdHandle, out num); SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, false); if (!consoleMode && !safeFileHandle.IsInvalid) { isHandleRedirected = true; handleInit(stdHandle); } isHandleRedirectionDetermined = true; } } ConsoleHost.tracer.WriteLine(isHandleRedirected); return isHandleRedirected; }
public static int Start([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] args, int argc) { if (args == null) { throw new ArgumentNullException(nameof(args)); } #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 // Warm up some components concurrently on background threads. EarlyStartup.Init(); // 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; ConsoleHost.ParseCommandLine(args); // NOTE: On Unix, logging depends on a command line parsing // and must be just after ConsoleHost.ParseCommandLine(args) // to allow overriding logging options. PSEtwLog.LogConsoleStartup(); int exitCode = 0; try { var banner = string.Format( CultureInfo.InvariantCulture, ManagedEntranceStrings.ShellBannerNonWindowsPowerShell, PSVersionInfo.GitCommitId); ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); exitCode = ConsoleHost.Start(banner, ManagedEntranceStrings.UsageHelp); } catch (HostException e) { if (e.InnerException is Win32Exception win32e) { // 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); }
internal ConsoleHostUserInterface(ConsoleHost parent) { this.errorForegroundColor = ConsoleColor.Red; this.warningForegroundColor = ConsoleColor.Yellow; this.debugForegroundColor = ConsoleColor.Yellow; this.verboseForegroundColor = ConsoleColor.Yellow; this.progressForegroundColor = ConsoleColor.Yellow; this.progressBackgroundColor = ConsoleColor.DarkCyan; this.instanceLock = new object(); this.parent = parent; this.rawui = new ConsoleHostRawUserInterface(this); ConsoleHostUserInterface.debugFormatString = ConsoleHostUserInterfaceStrings.DebugFormatString; ConsoleHostUserInterface.verboseFormatString = ConsoleHostUserInterfaceStrings.VerboseFormatString; ConsoleHostUserInterface.warningFormatString = ConsoleHostUserInterfaceStrings.WarningFormatString; this.isInteractiveTestToolListening = false; this.isTestingShiftTab = false; lastForegroundColor = this.rawui.ForegroundColor; lastBackgroundColor = this.RawUI.BackgroundColor; }