示例#1
0
        PostWrite(string value)
        {
            PostWrite();

            if (_parent.IsTranscribing)
            {
                try
                {
                    _parent.WriteToTranscript(value);
                }
                catch (Exception e)
                {
                    ConsoleHost.CheckForSevereException(e);
                    _parent.IsTranscribing = false;
                }
            }
        }
示例#2
0
        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;
                }
            }
        }
示例#3
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);
            }
            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 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");
        }
示例#5
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)
            {
                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);
        }
示例#6
0
        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();
            }
        }
示例#7
0
        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();
            }
        }
示例#8
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();
            }
        }