internal void DoExecute() { ExecutionContext.CheckStackDepth(); CommandProcessorBase currentCommandProcessor = this._context.CurrentCommandProcessor; try { this.Context.CurrentCommandProcessor = this; this.SetCurrentScopeToExecutionScope(); this.ProcessRecord(); } finally { this.Context.CurrentCommandProcessor = currentCommandProcessor; this.RestorePreviousScope(); } }
/// <summary> /// This method sets the execution scope to the /// appropriate scope for the pipeline and then calls /// the ProcessRecord abstract method that derived command processors /// override. /// </summary> internal void DoExecute() { ExecutionContext.CheckStackDepth(); CommandProcessorBase oldCurrentCommandProcessor = _context.CurrentCommandProcessor; try { Context.CurrentCommandProcessor = this; SetCurrentScopeToExecutionScope(); ProcessRecord(); } finally { Context.CurrentCommandProcessor = oldCurrentCommandProcessor; RestorePreviousScope(); } }
internal static PowerShell Convert(ScriptBlockAst body, ReadOnlyCollection <ParameterAst> functionParameters, bool isTrustedInput, ExecutionContext context, Dictionary <string, object> variables, bool filterNonUsingVariables, bool?createLocalScope, object[] args) { ExecutionContext.CheckStackDepth(); if (args == null) { args = Array.Empty <object>(); } // Perform validations on the ScriptBlock. GetSimplePipeline can allow for more than one // pipeline if the first parameter is true, but Invoke-Command doesn't yet support multiple // pipelines in a PowerShell (it just grabs the last command directly.) The rest of this // code properly supports multiple pipelines, so it should just work to change the false to true // if/when Invoke-Command can support multiple pipelines. string errorId; string errorMsg; body.GetSimplePipeline(true, out errorId, out errorMsg); if (errorId != null) { throw new ScriptBlockToPowerShellNotSupportedException(errorId, null, errorMsg); } var checker = new ScriptBlockToPowerShellChecker { ScriptBeingConverted = body }; if (functionParameters != null) { foreach (var parameter in functionParameters) { parameter.InternalVisit(checker); } } body.InternalVisit(checker); // When the context is null (or they haven't supplied any variables), throw, but only if we really need the // context (basically, if we have some variable reference to resolve). if (context == null && (checker.HasUsingExpr || checker.UsesParameter) && (variables == null)) { throw new PSInvalidOperationException(AutomationExceptions.CantConvertScriptBlockWithNoContext); } try { var converter = new ScriptBlockToPowerShellConverter { _context = context, _createLocalScope = createLocalScope }; if (checker.HasUsingExpr) { converter._usingValueMap = GetUsingValues(body, isTrustedInput, context, variables, filterNonUsingVariables).Item1; } if (checker.UsesParameter) { // If any parameters are used, we create a new scope and bind the parameters. var newScope = context.EngineSessionState.NewScope(false); context.EngineSessionState.CurrentScope = newScope; context.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal; var locals = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap); // Get the parameter metadata for the script block. // If 'functionParameters' is not null, then the ScriptBlockAst is actually the body of a FunctionDefinitionAst, and it doesn't have a ParamBlock. // If 'functionParameters' is null, then the ScriptBlockAst may have parameters defined in its ParamBlock. bool usesCmdletBinding = false; var parameters = functionParameters != null ? Compiler.GetParameterMetaData(functionParameters, true, ref usesCmdletBinding) : ((IParameterMetadataProvider)body).GetParameterMetadata(true, ref usesCmdletBinding); object[] remainingArgs = ScriptBlock.BindArgumentsForScriptblockInvoke( (RuntimeDefinedParameter[])parameters.Data, args, context, false, null, locals); locals.SetAutomaticVariable(AutomaticVariable.Args, remainingArgs, context); newScope.LocalsTuple = locals; } foreach (var pipeline in body.EndBlock.Statements.OfType <PipelineAst>()) { converter._powershell.AddStatement(); converter.ConvertPipeline(pipeline, isTrustedInput); } return(converter._powershell); } finally { if (checker.UsesParameter) { context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope); } } }
private void RunClause(Action <FunctionContext> clause, object dollarUnderbar, object inputToProcess) { ExecutionContext.CheckStackDepth(); _anyClauseExecuted = true; Pipe oldErrorOutputPipe = this.Context.ShellFunctionErrorOutputPipe; // If the script block has a different language mode than the current, // change the language mode. PSLanguageMode?oldLanguageMode = null; PSLanguageMode?newLanguageMode = null; if ((_scriptBlock.LanguageMode.HasValue) && (_scriptBlock.LanguageMode != Context.LanguageMode)) { oldLanguageMode = Context.LanguageMode; newLanguageMode = _scriptBlock.LanguageMode; } try { var oldScopeOrigin = this.Context.EngineSessionState.CurrentScope.ScopeOrigin; try { this.Context.EngineSessionState.CurrentScope.ScopeOrigin = this._dontUseScopeCommandOrigin ? CommandOrigin.Internal : this.Command.CommandOrigin; // Set the language mode. We do this before EnterScope(), so that the language // mode is appropriately applied for evaluation parameter defaults. if (newLanguageMode.HasValue) { Context.LanguageMode = newLanguageMode.Value; } bool?oldLangModeTransitionStatus = null; try { // If it's from ConstrainedLanguage to FullLanguage, indicate the transition before parameter binding takes place. if (oldLanguageMode == PSLanguageMode.ConstrainedLanguage && newLanguageMode == PSLanguageMode.FullLanguage) { oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding; Context.LanguageModeTransitionInParameterBinding = true; } EnterScope(); } finally { if (oldLangModeTransitionStatus.HasValue) { // Revert the transition state to old value after doing the parameter binding Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus.Value; } } if (commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output) { Context.RedirectErrorPipe(commandRuntime.OutputPipe); } else if (commandRuntime.ErrorOutputPipe.IsRedirected) { Context.RedirectErrorPipe(commandRuntime.ErrorOutputPipe); } if (dollarUnderbar != AutomationNull.Value) { _localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, _context); } else if (_dollarUnderbar != AutomationNull.Value) { _localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, _dollarUnderbar, _context); } if (inputToProcess != AutomationNull.Value) { if (inputToProcess == null) { inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator(); } else { IList list = inputToProcess as IList; inputToProcess = (list != null) ? list.GetEnumerator() : LanguagePrimitives.GetEnumerator(inputToProcess); } _localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, _context); } clause(_functionContext); } catch (TargetInvocationException tie) { // DynamicInvoke wraps exceptions, unwrap them here. throw tie.InnerException; } finally { Context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; if (oldLanguageMode.HasValue) { Context.LanguageMode = oldLanguageMode.Value; } Context.EngineSessionState.CurrentScope.ScopeOrigin = oldScopeOrigin; } } catch (ExitException ee) { if (!this.FromScriptFile || _rethrowExitException) { throw; } this._exitWasCalled = true; int exitCode = (int)ee.Argument; this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode); if (exitCode != 0) { this.commandRuntime.PipelineProcessor.ExecutionFailed = true; } } catch (FlowControlException) { throw; } catch (RuntimeException e) { // This method always throws. ManageScriptException(e); } catch (Exception e) { // This cmdlet threw an exception, so wrap it and bubble it up. throw ManageInvocationException(e); } }
private void RunClause(Action <FunctionContext> clause, object dollarUnderbar, object inputToProcess) { ExecutionContext.CheckStackDepth(); Pipe shellFunctionErrorOutputPipe = base.Context.ShellFunctionErrorOutputPipe; PSLanguageMode?nullable = null; PSLanguageMode?nullable2 = null; if (this._scriptBlock.LanguageMode.HasValue) { PSLanguageMode?languageMode = this._scriptBlock.LanguageMode; PSLanguageMode mode = base.Context.LanguageMode; if ((((PSLanguageMode)languageMode.GetValueOrDefault()) != mode) || !languageMode.HasValue) { nullable = new PSLanguageMode?(base.Context.LanguageMode); nullable2 = this._scriptBlock.LanguageMode; } } try { CommandOrigin scopeOrigin = base.Context.EngineSessionState.CurrentScope.ScopeOrigin; try { base.Context.EngineSessionState.CurrentScope.ScopeOrigin = base._dontUseScopeCommandOrigin ? CommandOrigin.Internal : base.Command.CommandOrigin; if (nullable2.HasValue) { base.Context.LanguageMode = nullable2.Value; } this.EnterScope(); if (base.commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output) { base.Context.RedirectErrorPipe(base.commandRuntime.OutputPipe); } else if (base.commandRuntime.ErrorOutputPipe.IsRedirected) { base.Context.RedirectErrorPipe(base.commandRuntime.ErrorOutputPipe); } if (dollarUnderbar != AutomationNull.Value) { this._localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, base._context); } if (inputToProcess != AutomationNull.Value) { if (inputToProcess == null) { inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator(); } else { IList list = inputToProcess as IList; inputToProcess = (list != null) ? list.GetEnumerator() : LanguagePrimitives.GetEnumerator(inputToProcess); } this._localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, base._context); } clause(this._functionContext); } catch (TargetInvocationException exception) { throw exception.InnerException; } finally { base.Context.RestoreErrorPipe(shellFunctionErrorOutputPipe); if (nullable.HasValue) { base.Context.LanguageMode = nullable.Value; } base.Context.EngineSessionState.CurrentScope.ScopeOrigin = scopeOrigin; } } catch (ExitException exception2) { if (!base.FromScriptFile || base._rethrowExitException) { throw; } base._exitWasCalled = true; int argument = (int)exception2.Argument; base.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, argument); if (argument != 0) { base.commandRuntime.PipelineProcessor.ExecutionFailed = true; } } catch (FlowControlException) { throw; } catch (RuntimeException exception3) { base.ManageScriptException(exception3); throw; } catch (Exception exception4) { CommandProcessorBase.CheckForSevereException(exception4); throw base.ManageInvocationException(exception4); } }
internal static PowerShell Convert(ScriptBlockAst body, IEnumerable <ParameterAst> functionParameters, ExecutionContext context, Dictionary <string, object> variables, bool filterNonUsingVariables, bool?createLocalScope, object[] args) { string str; string str2; PowerShell shell; ExecutionContext.CheckStackDepth(); if (args == null) { args = ScriptBlock.EmptyArray; } body.GetSimplePipeline(false, out str, out str2); if (str != null) { throw new ScriptBlockToPowerShellNotSupportedException(str, null, str2, new object[0]); } ScriptBlockToPowerShellChecker visitor = new ScriptBlockToPowerShellChecker { ScriptBeingConverted = body }; if (functionParameters != null) { foreach (ParameterAst ast in functionParameters) { ast.InternalVisit(visitor); } } body.InternalVisit(visitor); if (((context == null) && (visitor.HasUsingExpr || visitor.UsesParameter)) && (variables == null)) { throw new PSInvalidOperationException(AutomationExceptions.CantConvertScriptBlockWithNoContext); } try { ScriptBlockToPowerShellConverter converter = new ScriptBlockToPowerShellConverter { _context = context, _createLocalScope = createLocalScope }; if (visitor.HasUsingExpr) { converter._usingValues = GetUsingValues(body, context, variables, filterNonUsingVariables); } if (visitor.UsesParameter) { SessionStateScope scope = context.EngineSessionState.NewScope(false); context.EngineSessionState.CurrentScope = scope; context.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal; MutableTuple locals = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap); bool usesCmdletBinding = false; object[] objArray = ScriptBlock.BindArgumentsForScripblockInvoke((RuntimeDefinedParameter[])((IParameterMetadataProvider)body).GetParameterMetadata(true, ref usesCmdletBinding).Data, args, context, false, null, locals); locals.SetAutomaticVariable(AutomaticVariable.Args, objArray, context); scope.LocalsTuple = locals; } foreach (PipelineAst ast2 in body.EndBlock.Statements.OfType <PipelineAst>()) { converter._powershell.AddStatement(); converter.ConvertPipeline(ast2); } shell = converter._powershell; } finally { if (visitor.UsesParameter) { context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope); } } return(shell); }