internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime) { if ((lValue is NumberNode) && (rValue is NumberNode)) { int lNum = (int)((NumberNode) lValue).GetValue(context); int rNum = (int)((NumberNode) rValue).GetValue(context); if (lNum <= rNum) { for(; lNum <= rNum; lNum++) { commandRuntime.WriteObject(lNum); } } else { for(;lNum >= rNum; lNum--) { commandRuntime.WriteObject(lNum); } } return; } throw new InvalidOperationException("Can't execute 'range operator' for non-number values"); }
internal override object GetValue(ExecutionContext context) { AddItem(lValue.GetValue(context)); AddItem(rValue.GetValue(context)); return _array; }
internal override void Execute(Pash.Implementation.ExecutionContext context, ICommandRuntime commandRuntime) { ExecutionContext nestedContext = context.CreateNestedContext(); if (!(context.CurrentRunspace is LocalRunspace)) { throw new InvalidOperationException("Invalid context"); } // MUST: fix this with the commandRuntime Pipeline pipeline = context.CurrentRunspace.CreateNestedPipeline(); context.PushPipeline(pipeline); try { Command cmd = new Command("Get-Variable"); cmd.Parameters.Add("Name", new string[] { Text }); // TODO: implement command invoke pipeline.Commands.Add(cmd); commandRuntime.WriteObject(pipeline.Invoke(), true); //context.outputStreamWriter.Write(pipeline.Invoke(), true); } catch (Exception) { throw; } finally { context.PopPipeline(); } }
internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime) { ExecutionContext nestedContext = context.CreateNestedContext(); if (lValue is VariableNode) { VariableNode varNode = (VariableNode)lValue; if (! (context.CurrentRunspace is LocalRunspace)) throw new InvalidOperationException("Invalid context"); // MUST: fix this with the commandRuntime Pipeline pipeline = context.CurrentRunspace.CreateNestedPipeline(); context.PushPipeline(pipeline); try { Command cmd = new Command("Set-Variable"); cmd.Parameters.Add("Name", new string[] { varNode.Text }); cmd.Parameters.Add("Value", rValue.GetValue(context)); // TODO: implement command invoke pipeline.Commands.Add(cmd); pipeline.Invoke(); } catch (Exception) { throw; } finally { context.PopPipeline(); } } }
internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime) { // TODO: sum the values in both pipelines // TODO: if there are more than one value in the left - just copy left results and then the right results to the resulting pipe // TODO: if there is only one value on the left - convert the value on the right to the type of the left and then Sum commandRuntime.WriteObject(GetValue(context)); }
private void CreateOwnScope() { _originalContext = ExecutionContext; var executionSessionState = CommandInfo.Module != null ? CommandInfo.Module.SessionState : ExecutionContext.SessionState; _scopedContext = ExecutionContext.Clone(executionSessionState, _scriptBlockInfo.ScopeUsage); _scopedExecutionVisitor = new ExecutionVisitor(_scopedContext, CommandRuntime, false); }
// TODO: make sure to implement a Singleton DefaultRunspace pattern //internal static LocalRunspace DefaultRunspace { get; private set; } public LocalRunspace(PSHost host, RunspaceConfiguration configuration) { DefaultRunspace = this; PSHost = host; _runspaceConfiguration = configuration; ExecutionContext = new ExecutionContext(host, configuration); ExecutionContext.CurrentRunspace = this; }
internal SessionStateGlobal(ExecutionContext executionContext) { _executionContext = executionContext; _providers = new Dictionary<string, List<ProviderInfo>>(StringComparer.CurrentCultureIgnoreCase); _providerInstances = new Dictionary<string, List<CmdletProvider>>(StringComparer.CurrentCultureIgnoreCase); _providersCurrentDrive = new Dictionary<ProviderInfo, PSDriveInfo>(); _snapins = new Dictionary<string, PSSnapInInfo>(StringComparer.CurrentCultureIgnoreCase); }
// internals //internal Command Clone(); //internal Command(Command command); internal CommandProcessorBase CreateCommandProcessor(ExecutionContext executionContext, CommandManager commandFactory, bool addToHistory) { CommandProcessorBase cmdProcBase = commandFactory.CreateCommandProcessor(this); cmdProcBase.ExecutionContext = executionContext; cmdProcBase.AddParameters(Parameters); SetMergeResultOptions(cmdProcBase); cmdProcBase.RedirectionVisitor = RedirectionVisitor; return cmdProcBase; }
/// <summary> /// Executes the pipeline with regard to the processing lifecycle. /// </summary> /// <param name="context">The current ExecutionContext</param> /// <remarks> /// Read more about the lifecycle at http://msdn.microsoft.com/en-us/library/ms714429(v=vs.85).aspx /// </remarks> public void Execute(ExecutionContext context) { if (!_commandsToExecute.Any()) { return; } // redirect context input to first command's input _commandsToExecute[0].CommandRuntime.InputStream.Redirect(context.InputStream); // redirect output of last command to context var lastCommandRuntime = _commandsToExecute[_commandsToExecute.Count - 1].CommandRuntime; lastCommandRuntime.OutputStream.Redirect(context.OutputStream); // set correct ExecutionContext and direct all unclaimed error streams to the context error stream // TODO: think about whether it's okay that everyone uses simply the same context foreach (var curCommand in _commandsToExecute) { if (curCommand.CommandRuntime.ErrorStream.ClaimedBy == null) { curCommand.CommandRuntime.ErrorStream.Redirect(context.ErrorStream); } curCommand.ExecutionContext = context; } /* PREPARE - bind all cli args 1. Bind the named parameters. 2. Bind the positional parameters. 3. Bind the common parameters. 4. Bind the parameters to support calls to the ShouldProcess method. 5. Bind the named dynamic parameters 6. Bind the positional dynamic parameters. */ foreach (var curCommand in _commandsToExecute) { curCommand.Prepare(); } // BEGIN - call all BeginProcessing methods foreach (var curCommand in _commandsToExecute) { curCommand.BeginProcessing(); } /* PROCESS - process records from pipeline 1. Bind command-defined pipeline parameters. 2. Bind dynamic pipeline parameters. 3. Determine wether all necessary parameters are set 4. Call the real command's "ProcessRecord" method END - call all EndProcessing methods */ foreach (var curCommand in _commandsToExecute) { curCommand.ProcessRecords(); curCommand.EndProcessing(); } }
internal LocalRunspace(PSHost host, RunspaceConfiguration configuration, InitialSessionState initialSessionState) { DefaultRunspace = this; PSHost = host; if (configuration == null) _runspaceConfiguration = RunspaceFactory.DefaultRunspaceConfiguration; else _runspaceConfiguration = configuration; ExecutionContext = new ExecutionContext(host, configuration); ExecutionContext.CurrentRunspace = this; _initialSessionState = initialSessionState; }
internal override object GetValue(ExecutionContext context) { object leftVal = leftExpression.GetValue(context); object rightVal = rightExpression.GetValue(context); // TODO: need to generalize this via MethodInfo (somewhere in the compiler libraries via LanguageBasics) // usualy operators defined as: "public static int operator +", but in the MSIL are translated to op_Add MethodInfo mi = null; if (leftVal != null) { Type leftType = leftVal.GetType(); mi = leftType.GetMethod("op_Addition", new Type[] { leftType, leftType }); } else if (rightVal != null) { Type rightType = rightVal.GetType(); mi = rightType.GetMethod("op_Addition", new Type[] { rightType, rightType }); } else // If both of the values equal Null - return Null return null; if (mi == null) { if (leftVal != null) { if (leftVal is string) { return string.Concat(leftVal, rightVal.ToString()); } if (leftVal is int) { return (int)leftVal + Convert.ToInt32(rightVal); } } if (rightVal != null) { if (rightVal is string) { return string.Concat(leftVal.ToString(), rightVal); } if (rightVal is int) { return (int)rightVal + Convert.ToInt32(leftVal); } } throw new InvalidOperationException("The operator \"+\" is not defined for type " + leftVal.GetType().ToString()); } return null; }
public CommandManager(ExecutionContext context) { _context = context; _snapins = new Dictionary<string, PSSnapInInfo>(StringComparer.CurrentCultureIgnoreCase); _cmdLets = new Dictionary<string, List<CmdletInfo>>(StringComparer.CurrentCultureIgnoreCase); _scripts = new Dictionary<string, ScriptInfo>(StringComparer.CurrentCultureIgnoreCase); _aliases = new Dictionary<string, AliasInfo>(StringComparer.CurrentCultureIgnoreCase); _providers = new Collection<SnapinProviderPair>(); // if no execution scope is provided load all the initial settings from the config file if (context == null) { // TODO: move this to config.ps1 foreach (var snapinTypeName in new[] { "System.Management.Automation.PSCorePSSnapIn, System.Management.Automation", "Microsoft.PowerShell.PSUtilityPSSnapIn, Microsoft.PowerShell.Commands.Utility", "Microsoft.Commands.Management.PSManagementPSSnapIn, Microsoft.Commands.Management", }) { var tmpProviders = new Collection<SnapinProviderPair>(); // Load all PSSnapin's foreach (CmdletInfo cmdLetInfo in LoadCmdletsFromPSSnapin(snapinTypeName, out tmpProviders)) { // Register PSSnapin if (_snapins.ContainsKey(cmdLetInfo.PSSnapIn.Name)) { _snapins.Add(cmdLetInfo.PSSnapIn.Name, cmdLetInfo.PSSnapIn); } // Copy all the found Cmdlets List<CmdletInfo> cmdletList = null; if (_cmdLets.ContainsKey(cmdLetInfo.Name)) { cmdletList = _cmdLets[cmdLetInfo.Name]; } else { cmdletList = new List<CmdletInfo>(); _cmdLets.Add(cmdLetInfo.Name, cmdletList); } cmdletList.Add(cmdLetInfo); } foreach (SnapinProviderPair providerTypePair in tmpProviders) { _providers.Add(providerTypePair); } } } }
internal LocalRunspace(PSHost host, RunspaceConfiguration configuration, InitialSessionState initialSessionState) { //TODO: we should support both RunspaceConfigurations and IntialSessionStates properly _runningPipelines = new List<Pipeline>(); DefaultRunspace = this; PSHost = host; if (configuration == null) _runspaceConfiguration = RunspaceFactory.DefaultRunspaceConfiguration; else _runspaceConfiguration = configuration; ExecutionContext = new ExecutionContext(host, configuration); ExecutionContext.CurrentRunspace = this; _initialSessionState = initialSessionState; }
internal override object GetValue(ExecutionContext context) { if (_value == null) { // TODO: check the format of the number with RegEx. Possible: int, hex, real, etc... // TODO: deal with Octals? if (Text.StartsWith("0x")) _value = Int32.Parse(Text.Substring(2), NumberStyles.HexNumber); else _value = Int32.Parse(Text, NumberStyles.AllowHexSpecifier); } return _value; }
internal SessionStateGlobal(ExecutionContext context) : this() { _executionContext = context; if (context.SessionState == null) return; if (context.SessionState.SessionStateGlobal == null) return; _providers = context.SessionState.SessionStateGlobal._providers; _providersCurrentDrive = context.SessionState.SessionStateGlobal._providersCurrentDrive; _workingLocationStack = context.SessionState.SessionStateGlobal._workingLocationStack; _drives = context.SessionState.SessionStateGlobal._drives; _aliases = context.SessionState.SessionStateGlobal._aliases; _functions = context.SessionState.SessionStateGlobal._functions; _variables = context.SessionState.SessionStateGlobal._variables; }
internal CmdletInfo(string name, Type implementingType, string helpFile, PSSnapInInfo PSSnapin, ExecutionContext context) : base(name, CommandTypes.Cmdlet) { int i = name.IndexOf('-'); if (i == -1) { throw new Exception("InvalidCmdletNameFormat " + name); } Verb = name.Substring(0, i); Noun = name.Substring(i + 1); ImplementingType = implementingType; HelpFile = helpFile; PSSnapIn = PSSnapin; _context = context; ParameterSets = GetParameterSetInfo(implementingType); }
internal CmdletInfo(string name, Type implementingType, string helpFile, PSSnapInInfo PSSnapin, ExecutionContext context) : base(name, CommandTypes.Cmdlet) { int i = name.IndexOf('-'); if (i == -1) { throw new Exception("InvalidCmdletNameFormat " + name); } ParameterInfoLookupTable = new Dictionary<string, CommandParameterInfo>(StringComparer.CurrentCultureIgnoreCase); Verb = name.Substring(0, i); Noun = name.Substring(i + 1); ImplementingType = implementingType; HelpFile = helpFile; PSSnapIn = PSSnapin; _validationException = null; GetParameterSetInfo(implementingType); }
public Array Execute(ExecutionContext context) { PSObject psObjectCurrent = context.inputStreamReader.Read(); Collection<PSObject> dataCollection = new Collection<PSObject>() { psObjectCurrent} ; do { foreach (CommandProcessorBase commandProcessor in commandsToExecute) { PipelineCommandRuntime commandRuntime = new PipelineCommandRuntime(this); foreach (PSObject psObject in dataCollection) { // TODO: protect the execution context commandProcessor.ExecutionContext = context; // TODO: replace the Command default runtime to execute callbacks on the pipeline when the object is written to the pipeline and then execute the next cmdlet // TODO: provide a proper command initialization (for parameters and pipeline objects) commandProcessor.CommandRuntime = commandRuntime; commandProcessor.BindArguments(psObject); // TODO: for each entry in pipe // Execute the cmdlet at least once (even if there were nothing in the pipe commandProcessor.ProcessRecord(); } commandProcessor.Complete(); // TODO: process Error stream dataCollection = new PSObjectPipelineReader(commandRuntime.outputResults).ReadToEnd(); } } while ((psObjectCurrent = context.inputStreamReader.Read()) != null); // Write the final result to the output pipeline context.outputStreamWriter.Write(dataCollection, true); object[] dataResult = new object[dataCollection.Count]; int index = 0; foreach(PSObject obj in dataCollection) dataResult[index++] = obj; return dataResult; }
public static FormatGenerator Get(ExecutionContext context, FormatShape shape, FormatGeneratorOptions options) { if (_lastGenerator != null && _lastGenerator.Shape.Equals(shape) && _lastGenerator.Options.Equals(options)) { return _lastGenerator; } switch (shape) { case FormatShape.List: _lastGenerator = new ListFormatGenerator(context, options); break; case FormatShape.Table: _lastGenerator = new TableFormatGenerator(context, options); break; default: throw new PSInvalidOperationException("Cannot get a FormatGenerator with undefined shape"); } return _lastGenerator; }
internal override object GetValue(ExecutionContext context) { if (! _bExecuted) { if (! (context.CurrentRunspace is LocalRunspace)) throw new InvalidOperationException(string.Format("Command \"{0}\" was not found.", Text)); CommandManager cmdMgr = ((LocalRunspace) context.CurrentRunspace).CommandManager; CommandInfo cmdInfo = cmdMgr.FindCommand(Text); if (cmdInfo == null) throw new InvalidOperationException(string.Format("Command \"{0}\" was not found.", Text)); // MUST: fix this with the commandRuntime Pipeline pipeline = context.CurrentRunspace.CreateNestedPipeline(); // Fill the pipeline with input data pipeline.Input.Write(context.inputStreamReader); context.PushPipeline(pipeline); try { // TODO: implement command invoke pipeline.Commands.Add(Text); _results = pipeline.Invoke(); } catch (Exception) { throw; } finally { context.PopPipeline(); } _bExecuted = true; } return _results; }
internal CmdletProvider Add(ProviderInfo providerInfo, ExecutionContext executionContext) { CmdletProvider provider = providerInfo.CreateInstance(); var runtime = new ProviderRuntime(executionContext.SessionState); providerInfo = provider.Start(providerInfo, runtime); provider.SetProviderInfo(providerInfo); // Cache the Provider's Info and instance if (!_providers.ContainsKey(providerInfo.Name)) { _providers.Add(providerInfo.Name, new List<ProviderInfo>()); } _providers[providerInfo.Name].Add(providerInfo); _providerInstances[providerInfo] = provider; // provider is added, default drives can be added AddDefaultDrives(provider, runtime); return provider; }
internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime) { if (!(context.CurrentRunspace is LocalRunspace)) throw new InvalidOperationException(string.Format("Command \"{0}\" was not found.", CmdletName)); CommandManager cmdMgr = ((LocalRunspace)context.CurrentRunspace).CommandManager; CommandInfo cmdInfo = cmdMgr.FindCommand(CmdletName); if (cmdInfo == null) throw new InvalidOperationException(string.Format("Command \"{0}\" was not found.", CmdletName)); // MUST: fix this with the commandRuntime Pipeline pipeline = context.CurrentRunspace.CreateNestedPipeline(); context.PushPipeline(pipeline); try { // TODO: implement command invoke Command command = new Command(CmdletName); foreach (string param in Params.Params) { command.Parameters.Add(null, param); } pipeline.Commands.Add(command); _results = pipeline.Invoke(); commandRuntime.WriteObject(_results, true); } catch (Exception) { throw; } finally { context.PopPipeline(); } }
public ExecutionContext Clone(SessionState sessionState, ScopeUsages scopeUsage) { var sstate = (scopeUsage == ScopeUsages.CurrentScope) ? sessionState : new SessionState(sessionState); if (scopeUsage == ScopeUsages.NewScriptScope) { sstate.IsScriptScope = true; } var context = new ExecutionContext { InputStream = InputStream, OutputStream = OutputStream, ErrorStream = ErrorStream, CurrentRunspace = CurrentRunspace, LocalHost = LocalHost, WriteSideEffectsToPipeline = WriteSideEffectsToPipeline, SessionStateGlobal = SessionStateGlobal, SessionState = sstate }; // TODO: copy (not reference) all the variables to allow nested context <- what does it mean? return context; }
internal override object GetValue(ExecutionContext context) { Pipeline pipeline = context.CurrentRunspace.CreateNestedPipeline(); context.PushPipeline(pipeline); Collection<PSObject> results = nodeValue.GetValue(context) as Collection<PSObject>; context.PopPipeline(); if (results.Count == 0) return null; if (results.Count == 1) return results[0]; // TODO: make sure that the array.ToString calls the ToString on each PSObject PSObject[] array = new PSObject[results.Count]; int index = 0; foreach (PSObject psObject in results) { array[index++] = psObject; } return array; }
public override Collection <PSObject> Invoke(IEnumerable input) { // TODO: run the pipeline on another thread and wait for the completion // TODO: nested pipelines: make sure we are running in the same thread as another pipeline, because // nested pipelines aren't allowed to run in their own thread. This ensures that there is a "parent" pipeline Input.Write(input, true); // in a pipeline, the first command enters *always* the ProcessRecord phase, the following commands only // if the previous command generated output. To make sure the first command enters that phase, add null // if nothing else is in the input stream if (_inputStream.Count == 0) { Input.Write(null); } ExecutionContext context = _runspace.ExecutionContext.Clone(); RerouteExecutionContext(context); try { if (!_pipelineStateInfo.State.Equals(PipelineState.NotStarted)) { throw new InvalidPipelineStateException("Pipeline cannot be started", _pipelineStateInfo.State, PipelineState.NotStarted); } var pipelineProcessor = BuildPipelineProcessor(context); _runspace.AddRunningPipeline(this); SetPipelineState(PipelineState.Running); pipelineProcessor.Execute(context); SetPipelineState(PipelineState.Completed); } catch (FlowControlException ex) { if (IsNested) { throw; // propagate to parent levels } if (ex is ExitException) { // exit code must be an int. otherwise it's 0 int exitCode = 0; LanguagePrimitives.TryConvertTo <int>(((ExitException)ex).Argument, out exitCode); _runspace.PSHost.SetShouldExit(exitCode); } // at this point we are in the toplevel pipeline and we got a "return", "break", or "continue". // The behavior for this is that the pipeline stops (that's why we're here), but nothing else } catch (Exception ex) { // in case of throw statement, parse error, or "ThrowTerminatingError" // just add to error variable, the error stream and rethrow that thing context.AddToErrorVariable(ex); context.SetSuccessVariable(false); // last command was definitely not successfull throw; } _runspace.RemoveRunningPipeline(this); return(Output.NonBlockingRead()); }
internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime) { // TODO: rewrite this - it should expand the commands in the original pipe PipelineCommandRuntime subRuntime = null; foreach (ASTNode node in Pipeline) { ExecutionContext subContext = context.CreateNestedContext(); if (subRuntime == null) { subContext.inputStreamReader = context.inputStreamReader; } else { subContext.inputStreamReader = new PSObjectPipelineReader(subRuntime.outputResults); } subRuntime = new PipelineCommandRuntime(((PipelineCommandRuntime)commandRuntime).pipelineProcessor); subContext.inputStreamReader = subContext.inputStreamReader; node.Execute(subContext, subRuntime); } }
internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime) { context.outputStreamWriter.Write(GetValue(context), true); }
internal FormatManager(FormatShape shape, ExecutionContext context) { Shape = shape; Options = new FormatGeneratorOptions(); _state = FormattingState.FormatEnd; }
public void SetExecutionContext(ExecutionContext context) { _executionContext = context; }
internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime) { throw new NotImplementedException(); }
internal override void Execute(ExecutionContext context, ICommandRuntime commandRuntime) { commandRuntime.WriteObject(GetValue(context), true); }