internal static void AddArgumentsToCommandProcessor(CommandProcessorBase commandProcessor, object[] arguments) { if (arguments != null) { for (int i = 0; i < arguments.Length; i++) { CommandParameterInternal internal2; string arg = arguments[i] as string; if (ArgumentLooksLikeParameter(arg)) { int index = arg.IndexOf(':'); if ((index != -1) && (index != (arg.Length - 1))) { internal2 = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, arg.Substring(1, index - 1), arg, PositionUtilities.EmptyExtent, arg.Substring(index + 1).Trim(), false); } else if ((i == (arguments.Length - 1)) || (arg[arg.Length - 1] != ':')) { internal2 = CommandParameterInternal.CreateParameter(PositionUtilities.EmptyExtent, arg.Substring(1), arg); } else { internal2 = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, arg.Substring(1, arg.Length - 2), arg, PositionUtilities.EmptyExtent, arguments[i + 1], false); i++; } } else { internal2 = CommandParameterInternal.CreateArgument(PositionUtilities.EmptyExtent, arguments[i], false); } commandProcessor.AddParameter(internal2); } } }
private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadata result) { // MSFT:652277 - When invoking cmdlets or advanced functions, MyInvocation.MyCommand.Parameters do not contain the dynamic parameters // When trying to get parameter metadata for a CommandInfo that has dynamic parameters, a new CommandProcessor will be // created out of this CommandInfo and the parameter binding algorithm will be invoked. However, when this happens via // 'MyInvocation.MyCommand.Parameter', it's actually retrieving the parameter metadata of the same cmdlet that is currently // running. In this case, information about the specified parameters are not kept around in 'MyInvocation.MyCommand', so // going through the binding algorithm again won't give us the metadata about the dynamic parameters that should have been // discovered already. // The fix is to check if the CommandInfo is actually representing the currently running cmdlet. If so, the retrieval of parameter // metadata actually stems from the running of the same cmdlet. In this case, we can just use the current CommandProcessor to // retrieve all bindable parameters, which should include the dynamic parameters that have been discovered already. CommandProcessor processor; if (Context.CurrentCommandProcessor != null && Context.CurrentCommandProcessor.CommandInfo == this) { // Accessing the parameters within the invocation of the same cmdlet/advanced function. processor = (CommandProcessor)Context.CurrentCommandProcessor; } else { IScriptCommandInfo scriptCommand = this as IScriptCommandInfo; processor = scriptCommand != null ? new CommandProcessor(scriptCommand, _context, useLocalScope: true, fromScriptFile: false, sessionState: scriptCommand.ScriptBlock.SessionStateInternal ?? Context.EngineSessionState) : new CommandProcessor((CmdletInfo)this, _context) { UseLocalScope = true }; ParameterBinderController.AddArgumentsToCommandProcessor(processor, Arguments); CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor; try { Context.CurrentCommandProcessor = processor; processor.SetCurrentScopeToExecutionScope(); processor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(processor.arguments); } catch (ParameterBindingException) { // Ignore the binding exception if no argument is specified if (processor.arguments.Count > 0) { throw; } } finally { Context.CurrentCommandProcessor = oldCurrentCommandProcessor; processor.RestorePreviousScope(); } } result = processor.CmdletParameterBinderController.BindableParameters; }
internal CommandProcessorBase LookupCommandProcessor( string commandName, CommandOrigin commandOrigin, bool?useLocalScope) { CommandProcessorBase commandProcessorBase = this.LookupCommandProcessor(this.LookupCommandInfo(commandName, commandOrigin), commandOrigin, useLocalScope); commandProcessorBase.Command.MyInvocation.InvocationName = commandName; return(commandProcessorBase); }
internal void DoCleanup() { // The property 'PropagateExceptionsToEnclosingStatementBlock' controls whether a general exception // (an exception thrown from a .NET method invocation, or an expression like '1/0') will be turned // into a terminating error, which will be propagated up and thus stop the rest of the running script. // It is usually used by TryStatement and TrapStatement, which makes the general exception catch-able. // // For the 'Clean' block, we don't want to bubble up the general exception when the command is enclosed // in a TryStatement or has TrapStatement accompanying, because no exception can escape from 'Clean' and // thus it's pointless to bubble up the general exception in this case. // // Therefore we set this property to 'false' here to mask off the previous setting that could be from a // TryStatement or TrapStatement. Example: // PS:1> function b { end {} clean { 1/0; Write-Host 'clean' } } // PS:2> b // RuntimeException: Attempted to divide by zero. // clean // ## Note that, outer 'try/trap' doesn't affect the general exception happens in 'Clean' block. // ## so its behavior is consistent regardless of whether the command is enclosed by 'try/catch' or not. // PS:3> try { b } catch { 'outer catch' } // RuntimeException: Attempted to divide by zero. // clean // // Be noted that, this doesn't affect the TryStatement/TrapStatement within the 'Clean' block. Example: // ## 'try/trap' within 'Clean' block makes the general exception catch-able. // PS:3> function a { end {} clean { try { 1/0; Write-Host 'clean' } catch { Write-Host "caught: $_" } } } // PS:4> a // caught: Attempted to divide by zero. bool oldExceptionPropagationState = _context.PropagateExceptionsToEnclosingStatementBlock; _context.PropagateExceptionsToEnclosingStatementBlock = false; Pipe oldErrorOutputPipe = _context.ShellFunctionErrorOutputPipe; CommandProcessorBase oldCurrentCommandProcessor = _context.CurrentCommandProcessor; try { if (RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe is not null) { _context.ShellFunctionErrorOutputPipe = commandRuntime.ErrorOutputPipe; } _context.CurrentCommandProcessor = this; SetCurrentScopeToExecutionScope(); CleanResource(); } finally { _context.PropagateExceptionsToEnclosingStatementBlock = oldExceptionPropagationState; _context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; _context.CurrentCommandProcessor = oldCurrentCommandProcessor; RestorePreviousScope(); } }
/// <summary> /// Gets or creates a Job2 object with the given definition name, path /// and definition type if specified, that can be run via the StartJob() /// method. /// </summary> /// <param name="definitionName">Job definition name.</param> /// <param name="definitionPath">Job definition file path.</param> /// <param name="definitionType">JobSourceAdapter type that contains the job definition.</param> /// <param name="cmdlet">Cmdlet making call.</param> /// <param name="writeErrorOnException">Whether to write jobsourceadapter errors.</param> /// <returns>List of matching Job2 objects</returns> internal List <Job2> GetJobToStart( string definitionName, string definitionPath, string definitionType, Cmdlet cmdlet, bool writeErrorOnException) { List <Job2> jobs = new List <Job2>(); WildcardPattern typeNamePattern = (definitionType != null) ? WildcardPattern.Get(definitionType, WildcardOptions.IgnoreCase) : null; lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { try { if (typeNamePattern != null) { string sourceAdapterName = GetAdapterName(sourceAdapter); if (!typeNamePattern.IsMatch(sourceAdapterName)) { continue; } } Job2 job = sourceAdapter.NewJob(definitionName, definitionPath); if (job != null) { jobs.Add(job); } if (typeNamePattern != null) { // Adapter type found, can quit. break; } } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter); } } } return(jobs); }
} // NewSecurityDescriptor private ObjectSecurity NewSecurityDescriptorFromPath( CmdletProvider providerInstance, string path, AccessControlSections sections) { ObjectSecurity sd = null; // All parameters should have been validated by caller Diagnostics.Assert( providerInstance != null, "Caller should validate providerInstance before calling this method"); Diagnostics.Assert( path != null, "Caller should validate path before calling this method"); Diagnostics.Assert( ExecutionContext != null, "Caller should validate context before calling this method"); // This just verifies that the provider supports the interface. ISecurityDescriptorCmdletProvider sdProvider = GetPermissionProviderInstance(providerInstance); try { sd = sdProvider.NewSecurityDescriptorFromPath(path, sections); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "NewSecurityDescriptorProviderException", SessionStateStrings.GetSecurityDescriptorProviderException, providerInstance.ProviderInfo, path, e); } return(sd); } // NewSecurityDescriptor
} // SetPropertyDynamicParameters /// <summary> /// Gets the dynamic parameters for the set-itemproperty cmdlet. /// </summary> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="propertyValue"> /// The value of the property to set. /// </param> /// /// <param name="providerInstance"> /// The instance of the provider to use. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// /// <exception cref="NotSupportedException"> /// If the <paramref name="providerInstance"/> does not support this operation. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If the pipeline is being stopped while executing the command. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// private object SetPropertyDynamicParameters( CmdletProvider providerInstance, string path, PSObject propertyValue, CmdletProviderContext context) { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( providerInstance != null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( path != null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); object result = null; try { result = providerInstance.SetPropertyDynamicParameters(path, propertyValue, context); } catch (NotSupportedException) { throw; } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "SetPropertyDynamicParametersProviderException", SessionStateStrings.SetPropertyDynamicParametersProviderException, providerInstance.ProviderInfo, path, e); } return(result); } // SetPropertyDynamicParameters
public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) { if (contextToRedirectTo == null) { throw new ArgumentNullException(nameof(contextToRedirectTo)); } CommandProcessorBase commandProcessor = contextToRedirectTo.SessionState.Internal.ExecutionContext.CurrentCommandProcessor; ICommandRuntime commandRuntime = commandProcessor == null ? (ICommandRuntime)null : (ICommandRuntime)commandProcessor.CommandRuntime; this.Begin(expectInput, commandRuntime); }
private void Parse(string script) { try { this._parser.ParseScriptBlock(script, false); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); } }
} // ClearProperty /// <summary> /// Clears the value of the property from the item at the specified path. /// </summary> /// /// <param name="providerInstance"> /// The provider instance to use. /// </param> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="propertyToClear"> /// The name of the property to clear. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <exception cref="NotSupportedException"> /// If the <paramref name="providerInstance"/> does not support this operation. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If the pipeline is being stopped while executing the command. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// private void ClearPropertyPrivate( CmdletProvider providerInstance, string path, Collection <string> propertyToClear, CmdletProviderContext context) { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( providerInstance != null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( path != null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( propertyToClear != null, "Caller should validate propertyToClear before calling this method"); Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); try { providerInstance.ClearProperty(path, propertyToClear, context); } catch (NotSupportedException) { throw; } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "ClearPropertyProviderException", SessionStateStrings.ClearPropertyProviderException, providerInstance.ProviderInfo, path, e); } } // ClearPropertyPrivate
internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, CommandOrigin commandOrigin) { PipelineProcessor pipe = new PipelineProcessor(); System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS(); foreach (CommandAst ast in pipelineAst.PipelineElements.Cast <CommandAst>()) { List <CommandParameterInternal> list = new List <CommandParameterInternal>(); foreach (CommandElementAst ast2 in ast.CommandElements) { CommandParameterAst commandParameterAst = ast2 as CommandParameterAst; if (commandParameterAst != null) { list.Add(GetCommandParameter(commandParameterAst, executionContextFromTLS)); } else { ExpressionAst expressionAst = (ExpressionAst)ast2; object obj2 = Compiler.GetExpressionValue(expressionAst, executionContextFromTLS, (IList)null); bool splatted = (expressionAst is VariableExpressionAst) && ((VariableExpressionAst)expressionAst).Splatted; list.Add(CommandParameterInternal.CreateArgument(expressionAst.Extent, obj2, splatted)); } } List <CommandRedirection> list2 = new List <CommandRedirection>(); foreach (RedirectionAst ast5 in ast.Redirections) { list2.Add(GetCommandRedirection(ast5, executionContextFromTLS)); } CommandProcessorBase base2 = AddCommand(pipe, list.ToArray(), ast, list2.ToArray(), executionContextFromTLS); base2.Command.CommandOriginInternal = commandOrigin; base2.CommandScope.ScopeOrigin = commandOrigin; base2.Command.MyInvocation.CommandOrigin = commandOrigin; CallStackFrame[] frameArray = executionContextFromTLS.Debugger.GetCallStack().ToArray <CallStackFrame>(); if ((frameArray.Length > 0) && Regex.IsMatch(frameArray[0].Position.Text, "GetSteppablePipeline", RegexOptions.IgnoreCase)) { InvocationInfo myInvocation = base2.Command.MyInvocation; myInvocation.InvocationName = frameArray[0].InvocationInfo.InvocationName; if (frameArray.Length > 1) { IScriptExtent position = frameArray[1].Position; if ((position != null) && (position != PositionUtilities.EmptyExtent)) { myInvocation.DisplayScriptPosition = position; } } } if ((executionContextFromTLS.CurrentCommandProcessor != null) && (executionContextFromTLS.CurrentCommandProcessor.CommandRuntime != null)) { base2.CommandRuntime.SetMergeFromRuntime(executionContextFromTLS.CurrentCommandProcessor.CommandRuntime); } } return(new SteppablePipeline(executionContextFromTLS, pipe)); }
internal object BaseMethodInvoke(PSMethod method, params object[] arguments) { try { return(this.MethodInvoke(method, arguments)); } catch (TargetInvocationException ex) { Exception innerException = ex.InnerException == null ? (Exception)ex : ex.InnerException; throw new MethodInvocationException("CatchFromBaseAdapterMethodInvokeTI", innerException, "ExtendedTypeSystem", "MethodInvocationException", new object[3] { (object)method.Name, (object)arguments.Length, (object)innerException.Message }); } catch (FlowControlException ex) { throw; } catch (ScriptCallDepthException ex) { throw; } catch (PipelineStoppedException ex) { throw; } catch (Exception ex) { if (ex is MethodException) { throw; } else { CommandProcessorBase.CheckForSevereException(ex); if (method.baseObject is SteppablePipeline && (method.Name.Equals("Begin", StringComparison.OrdinalIgnoreCase) || method.Name.Equals("Process", StringComparison.OrdinalIgnoreCase) || method.Name.Equals("End", StringComparison.OrdinalIgnoreCase))) { throw; } else { throw new MethodInvocationException("CatchFromBaseAdapterMethodInvoke", ex, "ExtendedTypeSystem", "MethodInvocationException", new object[3] { (object)method.Name, (object)arguments.Length, (object)ex.Message }); } } } }
internal void SetJobState(JobState state, Exception reason) { using (PowerShellTraceSource source = PowerShellTraceSourceFactory.GetTraceSource()) { this.AssertNotDisposed(); bool flag = false; System.Management.Automation.JobStateInfo stateInfo = this.stateInfo; lock (this.syncObject) { this.stateInfo = new System.Management.Automation.JobStateInfo(state, reason); if (state == JobState.Running) { if (!this.PSBeginTime.HasValue) { this.PSBeginTime = new DateTime?(DateTime.Now); } } else if (this.IsFinishedState(state)) { flag = true; if (!this.PSEndTime.HasValue) { this.PSEndTime = new DateTime?(DateTime.Now); } } } if (flag) { this.CloseAllStreams(); } try { source.WriteMessage("Job", "SetJobState", Guid.Empty, this, "Invoking StateChanged event", null); this.StateChanged.SafeInvoke <JobStateEventArgs>(this, new JobStateEventArgs(this.stateInfo.Clone(), stateInfo)); } catch (Exception exception) { source.WriteMessage("Job", "SetJobState", Guid.Empty, this, "Some Job StateChange event handler threw an unhandled exception.", null); source.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); } if (flag) { lock (this.syncObject) { if (this.finished != null) { this.finished.Set(); } } } } }
private void Init(IScriptCommandInfo scriptCommandInfo) { InternalCommand command = new PSScriptCmdlet(scriptCommandInfo.ScriptBlock, base._useLocalScope, base.FromScriptFile, base._context); base.Command = command; base.CommandScope = base._useLocalScope ? base.CommandSessionState.NewScope(base._fromScriptFile) : base.CommandSessionState.CurrentScope; this.InitCommon(); if (!base.UseLocalScope) { CommandProcessorBase.ValidateCompatibleLanguageMode(scriptCommandInfo.ScriptBlock, base._context.LanguageMode, base.Command.MyInvocation); } }
/// <summary> /// Raises events for changes in execution state. /// </summary> protected void RaisePipelineStateEvents() { Queue <ExecutionEventQueueItem> tempEventQueue = null; EventHandler <PipelineStateEventArgs> stateChanged = null; bool runspaceHasAvailabilityChangedSubscribers = false; lock (_syncRoot) { stateChanged = this.StateChanged; runspaceHasAvailabilityChangedSubscribers = _runspace.HasAvailabilityChangedSubscribers; if (stateChanged != null || runspaceHasAvailabilityChangedSubscribers) { tempEventQueue = _executionEventQueue; _executionEventQueue = new Queue <ExecutionEventQueueItem>(); } else { //Clear the events if there are no EventHandlers. This //ensures that events do not get called for state //changes prior to their registration. _executionEventQueue.Clear(); } } if (tempEventQueue != null) { while (tempEventQueue.Count > 0) { ExecutionEventQueueItem queueItem = tempEventQueue.Dequeue(); if (runspaceHasAvailabilityChangedSubscribers && queueItem.NewRunspaceAvailability != queueItem.CurrentRunspaceAvailability) { _runspace.RaiseAvailabilityChangedEvent(queueItem.NewRunspaceAvailability); } //Exception raised in the eventhandler are not error in pipeline. //silently ignore them. if (stateChanged != null) { try { stateChanged(this, new PipelineStateEventArgs(queueItem.PipelineStateInfo)); } catch (Exception exception) // ignore non-severe exceptions { CommandProcessorBase.CheckForSevereException(exception); } } } } }
/// <summary> /// Gets the security descriptor from the specified item. /// </summary> /// /// <param name="type"> /// The type of the item which corresponds to the security /// descriptor that we want to create. /// </param> /// /// <param name="providerInstance"> /// The type of the item which corresponds to the security /// descriptor that we want to create. /// </param> /// /// <param name="sections"> /// Specifies the parts of a security descriptor to retrieve. /// </param> /// /// <returns> /// Nothing. The security descriptor for the item at the specified type is /// written to the context. /// </returns> /// internal ObjectSecurity NewSecurityDescriptorOfType( CmdletProvider providerInstance, string type, AccessControlSections sections) { ObjectSecurity sd = null; if (type == null) { throw PSTraceSource.NewArgumentNullException("type"); } if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException("providerInstance"); } // This just verifies that the provider supports the interface. ISecurityDescriptorCmdletProvider sdProvider = GetPermissionProviderInstance(providerInstance); try { sd = sdProvider.NewSecurityDescriptorOfType(type, sections); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "NewSecurityDescriptorProviderException", SessionStateStrings.GetSecurityDescriptorProviderException, providerInstance.ProviderInfo, type, e); } return(sd); } // NewSecurityDescriptorOfType
private void Init(CmdletInfo cmdletInformation) { Cmdlet cmdlet = (Cmdlet)null; Exception exception = (Exception)null; string errorIdAndResourceId = "CmdletNotFoundException"; try { cmdlet = (Cmdlet)Activator.CreateInstance(cmdletInformation.ImplementingType); } catch (TargetInvocationException ex) { CommandProcessor.tracer.TraceException((Exception)ex); CmdletInvocationException invocationException = new CmdletInvocationException(ex.InnerException, (InvocationInfo)null); MshLog.LogCommandHealthEvent(this.context, (Exception)invocationException, Severity.Warning); throw invocationException; } catch (MemberAccessException ex) { exception = (Exception)ex; } catch (TypeLoadException ex) { exception = (Exception)ex; } catch (InvalidCastException ex) { exception = (Exception)ex; errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType"; } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); CommandProcessor.tracer.TraceException(ex); MshLog.LogCommandHealthEvent(this.context, ex, Severity.Warning); throw; } if (exception != null) { CommandProcessor.tracer.TraceException(exception); MshLog.LogCommandHealthEvent(this.context, exception, Severity.Warning); CommandNotFoundException notFoundException = new CommandNotFoundException(cmdletInformation.Name, exception, errorIdAndResourceId, new object[1] { (object)exception.Message }); CommandProcessor.tracer.TraceException((Exception)notFoundException); throw notFoundException; } this.Command = (InternalCommand)cmdlet; this.InitCommon(); }
private Job2 GetJobThroughId <T>(Guid guid, int id, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse) { Diagnostics.Assert(cmdlet != null, "Cmdlet should always be passed to JobManager"); Job2 job = null; lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { try { if (typeof(T) == typeof(Guid)) { Diagnostics.Assert(id == 0, "id must be zero when invoked with guid"); job = sourceAdapter.GetJobByInstanceId(guid, recurse); } else if (typeof(T) == typeof(int)) { Diagnostics.Assert(guid == Guid.Empty, "Guid must be empty when used with int"); job = sourceAdapter.GetJobBySessionId(id, recurse); } } catch (Exception exception) { // Since we are calling into 3rd party code // catching Exception is allowed. In all // other cases the appropriate exception // needs to be caught. // sourceAdapter.GetJobByInstanceId threw unknown exception. _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter); } if (job == null) { continue; } if (writeObject) { cmdlet.WriteObject(job); } return(job); } } return(null); }
internal static void InvokePipeline(object input, bool ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext) { PipelineProcessor pipelineProcessor = new PipelineProcessor(); System.Management.Automation.ExecutionContext context = funcContext._executionContext; Pipe pipe = funcContext._outputPipe; try { if (context.Events != null) { context.Events.ProcessPendingActions(); } if ((input == AutomationNull.Value) && !ignoreInput) { AddNoopCommandProcessor(pipelineProcessor, context); } CommandProcessorBase commandProcessor = null; CommandRedirection[] redirections = null; for (int i = 0; i < pipeElements.Length; i++) { redirections = (commandRedirections != null) ? commandRedirections [i] : null; commandProcessor = AddCommand(pipelineProcessor, pipeElements [i], pipeElementAsts [i], redirections, context); } if ((commandProcessor != null) && !commandProcessor.CommandRuntime.OutputPipe.IsRedirected) { pipelineProcessor.LinkPipelineSuccessOutput(pipe ?? new Pipe(new ArrayList())); if (redirections != null) { foreach (CommandRedirection redirection in redirections) { if (redirection is MergingRedirection) { redirection.Bind(pipelineProcessor, commandProcessor, context); } } } } context.PushPipelineProcessor(pipelineProcessor); try { pipelineProcessor.SynchronousExecuteEnumerate(input, null, true); } finally { context.PopPipelineProcessor(false); } } finally { context.QuestionMarkVariableValue = !pipelineProcessor.ExecutionFailed; pipelineProcessor.Dispose(); } }
internal override void DoStopProcessing() { try { if (this.myCommandProcessor != null) { this.myCommandProcessor.StopProcessing(); } } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } }
internal CommandProcessorBase CreateCommand(string command, bool dotSource) { if (this.commandFactory == null) { this.commandFactory = new CommandFactory(this); } CommandProcessorBase base2 = this.commandFactory.CreateCommand(command, this.EngineSessionState.CurrentScope.ScopeOrigin, new bool?(!dotSource)); if ((base2 != null) && (base2 is ScriptCommandProcessorBase)) { base2.Command.CommandOriginInternal = CommandOrigin.Internal; } return(base2); }
private void Parse(string script) { try { Parser parser2 = new Parser { ProduceV2Tokens = true }; parser2.Parse(null, script, this.tokenList, out this.errors); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } }
private void CleanUp() { try { if (this.nativeProcess != null) { this.nativeProcess.Close(); } } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } }
public static AnalysisCacheIndex GetCacheIndexFromDisk(string basePath) { AnalysisCacheIndex cacheIndex = null; bool flag = false; try { ModuleIntrinsics.Tracer.WriteLine("Deserializing cache index from " + Path.Combine(basePath, "PowerShell_AnalysisCacheIndex"), new object[0]); cacheIndex = DeserializeFromFile <AnalysisCacheIndex>(basePath, "PowerShell_AnalysisCacheIndex"); } catch (Exception exception) { ModuleIntrinsics.Tracer.WriteLine("Got an exception deserializing index: " + exception.ToString(), new object[0]); CommandProcessorBase.CheckForSevereException(exception); flag = true; } if (cacheIndex == null) { ModuleIntrinsics.Tracer.WriteLine("Creating new index, couldn't get one from disk.", new object[0]); cacheIndex = new AnalysisCacheIndex { LastMaintenance = DateTime.Now }; } if (cacheIndex.Entries == null) { cacheIndex.Entries = new Dictionary <string, AnalysisCacheIndexEntry>(StringComparer.OrdinalIgnoreCase); } if (!flag) { TimeSpan span = (TimeSpan)(DateTime.Now - cacheIndex.LastMaintenance); if (span.TotalDays <= 7.0) { return(cacheIndex); } } if (flag) { ModuleIntrinsics.Tracer.WriteLine("Cleaning analysis store because it was corrupted.", new object[0]); } else { ModuleIntrinsics.Tracer.WriteLine("Cleaning analysis store for its 7-day maintenance window. Last maintenance was " + cacheIndex.LastMaintenance, new object[0]); } if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PSDisableModuleAutoloadingCacheMaintenance"))) { CleanAnalysisCacheStore(cacheIndex); } return(cacheIndex); }
internal void RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, bool throwExceptions = false) { bool flag = false; lock (this._syncObject) { foreach (JobSourceAdapter adapter in this._sourceAdapters.Values) { Job2 jobByInstanceId = null; try { jobByInstanceId = adapter.GetJobByInstanceId(job.InstanceId, true); } catch (Exception exception) { this.Tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); if (throwExceptions) { throw; } WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobError", adapter); } if (jobByInstanceId != null) { flag = true; this.RemoveJobIdForReuse(jobByInstanceId); try { adapter.RemoveJob(job); } catch (Exception exception2) { this.Tracer.TraceException(exception2); CommandProcessorBase.CheckForSevereException(exception2); if (throwExceptions) { throw; } WriteErrorOrWarning(writeErrorOnException, cmdlet, exception2, "JobSourceAdapterRemoveJobError", adapter); } } } } if (!flag && throwExceptions) { throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ItemNotFoundInRepository, new object[] { "Job repository", job.InstanceId.ToString() })); } }
private void Parse(string script) { try { var parser = new Language.Parser { ProduceV2Tokens = true }; parser.Parse(null, script, _tokenList, out _errors, ParseMode.Default); } catch (Exception e) { // Catch everything, die on fatal exceptions, otherwise ignore CommandProcessorBase.CheckForSevereException(e); } }
private void ReaderStartProc() { try { this.ReaderStartProcHelper(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } finally { this.processOutputReader.ReaderDone(this.isOutput); } }
private void OnJobDataAdded(JobDataAddedEventArgs eventArgs) { try { this._tracer.WriteMessage("PSChildJobProxy", "OnJobDataAdded", Guid.Empty, this, "BEGIN call event handlers", new string[0]); this.JobDataAdded.SafeInvoke <JobDataAddedEventArgs>(this, eventArgs); this._tracer.WriteMessage("PSChildJobProxy", "OnJobDataAdded", Guid.Empty, this, "END call event handlers", new string[0]); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); this._tracer.WriteMessage("PSChildJobProxy", "OnJobDataAdded", Guid.Empty, this, "END Exception thrown in JobDataAdded handler", new string[0]); this._tracer.TraceException(exception); } }
internal object GetArrayElement(Array array, object index, out bool failed) { failed = false; try { if (array.Rank == 1) { int index1 = (int)LanguagePrimitives.ConvertTo(index, typeof(int), (IFormatProvider)NumberFormatInfo.InvariantInfo); if (index1 < 0) { index1 += array.Length; } return(array.GetValue(index1)); } int[] numArray = (int[])LanguagePrimitives.ConvertTo(index, typeof(int[]), (IFormatProvider)NumberFormatInfo.InvariantInfo); return(array.GetValue(numArray)); } catch (ScriptCallDepthException ex) { throw; } catch (FlowControlException ex) { throw; } catch (RuntimeException ex) { throw; } catch (InvalidCastException ex) { failed = true; } catch (ArgumentException ex) { this.ReportIndexingError(array, index, (Exception)ex); } catch (IndexOutOfRangeException ex) { failed = true; } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); failed = true; } return((object)null); }
/// <summary> /// Implement the stop functionality for native commands... /// </summary> internal override void DoStopProcessing() { try { if (_myCommandProcessor != null) { _myCommandProcessor.StopProcessing(); } } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); // Ignore exceptions here... ; } }
private void DoSetValue(IDictionary dictionary, object index, object value) { try { dictionary[index] = value; } catch (InvalidCastException ex) { throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), this.NodeToken, "KeyTypeMismatch", (Exception)ex, (object)dictionary.GetType().Name, (object)index.GetType().Name); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), this.NodeToken, "ArrayAssignmentFailed", ex, index, (object)ex.Message); } }
internal override void Bind(System.Management.Automation.Internal.PipelineProcessor pipelineProcessor, CommandProcessorBase commandProcessor, ExecutionContext context) { Pipe redirectionPipe = this.GetRedirectionPipe(context, pipelineProcessor); switch (base.FromStream) { case RedirectionStream.All: commandProcessor.CommandRuntime.OutputPipe = redirectionPipe; commandProcessor.CommandRuntime.ErrorOutputPipe = redirectionPipe; commandProcessor.CommandRuntime.WarningOutputPipe = redirectionPipe; commandProcessor.CommandRuntime.VerboseOutputPipe = redirectionPipe; commandProcessor.CommandRuntime.DebugOutputPipe = redirectionPipe; return; case RedirectionStream.Output: commandProcessor.CommandRuntime.OutputPipe = redirectionPipe; return; case RedirectionStream.Error: commandProcessor.CommandRuntime.ErrorOutputPipe = redirectionPipe; return; case RedirectionStream.Warning: commandProcessor.CommandRuntime.WarningOutputPipe = redirectionPipe; return; case RedirectionStream.Verbose: commandProcessor.CommandRuntime.VerboseOutputPipe = redirectionPipe; return; case RedirectionStream.Debug: commandProcessor.CommandRuntime.DebugOutputPipe = redirectionPipe; break; case RedirectionStream.Host: break; default: return; } }
internal override void Bind(PipelineProcessor pipelineProcessor, CommandProcessorBase commandProcessor, ExecutionContext context) { Pipe outputPipe = commandProcessor.CommandRuntime.OutputPipe; switch (base.FromStream) { case RedirectionStream.All: commandProcessor.CommandRuntime.ErrorMergeTo = MshCommandRuntime.MergeDataStream.Output; commandProcessor.CommandRuntime.WarningOutputPipe = outputPipe; commandProcessor.CommandRuntime.VerboseOutputPipe = outputPipe; commandProcessor.CommandRuntime.DebugOutputPipe = outputPipe; return; case RedirectionStream.Output: case RedirectionStream.Host: break; case RedirectionStream.Error: commandProcessor.CommandRuntime.ErrorMergeTo = MshCommandRuntime.MergeDataStream.Output; return; case RedirectionStream.Warning: commandProcessor.CommandRuntime.WarningOutputPipe = outputPipe; return; case RedirectionStream.Verbose: commandProcessor.CommandRuntime.VerboseOutputPipe = outputPipe; return; case RedirectionStream.Debug: commandProcessor.CommandRuntime.DebugOutputPipe = outputPipe; break; default: return; } }
/// <summary> /// Reparses the arguments specified in the object[] and generates CommandParameterInternal instances /// based on whether the arguments look like parameters. The CommandParameterInternal instances then /// get added to the specified command processor. /// </summary> /// /// <param name="commandProcessor"> /// The command processor instance to add the reparsed parameters to. /// </param> /// /// <param name="arguments"> /// The arguments that require reparsing. /// </param> /// internal static void AddArgumentsToCommandProcessor(CommandProcessorBase commandProcessor, object[] arguments) { if ((arguments != null) && (arguments.Length > 0)) { PSBoundParametersDictionary boundParameters = arguments[0] as PSBoundParametersDictionary; if ((boundParameters != null) && (arguments.Length == 1)) { // If they are supplying a dictionary of parameters, use those directly foreach (KeyValuePair<string, object> boundParameter in boundParameters) { CommandParameterInternal param = CommandParameterInternal.CreateParameterWithArgument( PositionUtilities.EmptyExtent, boundParameter.Key, boundParameter.Key, PositionUtilities.EmptyExtent, boundParameter.Value, false); commandProcessor.AddParameter(param); } } else { // Otherwise, we need to parse them ourselves for (int argIndex = 0; argIndex < arguments.Length; ++argIndex) { CommandParameterInternal param; string paramText = arguments[argIndex] as string; if (ArgumentLooksLikeParameter(paramText)) { // The argument looks like a parameter. // Create a parameter with argument if the paramText is like this: -Path:c:\windows // Combine it with the next argument if there is an argument, and the parameter ends in ':'. var colonIndex = paramText.IndexOf(':'); if (colonIndex != -1 && colonIndex != paramText.Length - 1) { param = CommandParameterInternal.CreateParameterWithArgument( PositionUtilities.EmptyExtent, paramText.Substring(1, colonIndex - 1), paramText, PositionUtilities.EmptyExtent, paramText.Substring(colonIndex + 1).Trim(), false); } else if (argIndex == arguments.Length - 1 || paramText[paramText.Length - 1] != ':') { param = CommandParameterInternal.CreateParameter( PositionUtilities.EmptyExtent, paramText.Substring(1), paramText); } else { param = CommandParameterInternal.CreateParameterWithArgument( PositionUtilities.EmptyExtent, paramText.Substring(1, paramText.Length - 2), paramText, PositionUtilities.EmptyExtent, arguments[argIndex + 1], false); argIndex++; } } else { param = CommandParameterInternal.CreateArgument( PositionUtilities.EmptyExtent, arguments[argIndex]); } commandProcessor.AddParameter(param); } } } }
private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop) { for (int i = 0; i < this._commands.Count; i++) { CommandProcessorBase objB = this._commands[i]; if (objB == null) { throw PSTraceSource.NewInvalidOperationException(); } if (object.ReferenceEquals(commandRequestingUpstreamCommandsToStop, objB)) { commandRequestingUpstreamCommandsToStop = null; } else if (commandRequestingUpstreamCommandsToStop == null) { try { objB.DoComplete(); } catch (PipelineStoppedException) { StopUpstreamCommandsException firstTerminatingError = this.firstTerminatingError as StopUpstreamCommandsException; if (firstTerminatingError == null) { throw; } this.firstTerminatingError = null; commandRequestingUpstreamCommandsToStop = firstTerminatingError.RequestingCommandProcessor; } EtwActivity.SetActivityId(objB.PipelineActivityId); MshLog.LogCommandLifecycleEvent(objB.Command.Context, CommandState.Stopped, objB.Command.MyInvocation); } } if (this.firstTerminatingError != null) { this.LogExecutionException(this.firstTerminatingError); throw this.firstTerminatingError; } }
internal int Add(CommandProcessorBase commandProcessor) { commandProcessor.CommandRuntime.PipelineProcessor = this; return this.AddCommand(commandProcessor, this._commands.Count, false); }
internal int AddCommand(CommandProcessorBase commandProcessor, int readFromCommand, bool readErrorQueue) { if (commandProcessor == null) { throw PSTraceSource.NewArgumentNullException("commandProcessor"); } if (this._commands == null) { throw PSTraceSource.NewInvalidOperationException(); } if (this.disposed) { throw PSTraceSource.NewObjectDisposedException("PipelineProcessor"); } if (this.executionStarted) { throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "ExecutionAlreadyStarted", new object[0]); } if (commandProcessor.AddedToPipelineAlready) { throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "CommandProcessorAlreadyUsed", new object[0]); } if (this._commands.Count == 0) { if (readFromCommand != 0) { throw PSTraceSource.NewArgumentException("readFromCommand", "PipelineStrings", "FirstCommandCannotHaveInput", new object[0]); } commandProcessor.AddedToPipelineAlready = true; } else { if ((readFromCommand > this._commands.Count) || (readFromCommand <= 0)) { throw PSTraceSource.NewArgumentException("readFromCommand", "PipelineStrings", "InvalidCommandNumber", new object[0]); } CommandProcessorBase base2 = this._commands[readFromCommand - 1]; if ((base2 == null) || (base2.CommandRuntime == null)) { throw PSTraceSource.NewInvalidOperationException(); } Pipe pipe = readErrorQueue ? base2.CommandRuntime.ErrorOutputPipe : base2.CommandRuntime.OutputPipe; if (pipe == null) { throw PSTraceSource.NewInvalidOperationException(); } if (pipe.DownstreamCmdlet != null) { throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "PipeAlreadyTaken", new object[0]); } commandProcessor.AddedToPipelineAlready = true; commandProcessor.CommandRuntime.InputPipe = pipe; pipe.DownstreamCmdlet = commandProcessor; if (commandProcessor.CommandRuntime.MergeUnclaimedPreviousErrorResults) { for (int i = 0; i < this._commands.Count; i++) { base2 = this._commands[i]; if ((base2 == null) || (base2.CommandRuntime == null)) { throw PSTraceSource.NewInvalidOperationException(); } if ((base2.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet == null) && (base2.CommandRuntime.ErrorOutputPipe.ExternalWriter == null)) { base2.CommandRuntime.ErrorOutputPipe = pipe; } } } } this._commands.Add(commandProcessor); commandProcessor.CommandRuntime.PipelineProcessor = this; return this._commands.Count; }
internal abstract void Bind(PipelineProcessor pipelineProcessor, CommandProcessorBase commandProcessor, ExecutionContext context);
private void SetMergeSettingsOnCommandProcessor(CommandProcessorBase commandProcessor) { MshCommandRuntime commandRuntime = commandProcessor.Command.commandRuntime as MshCommandRuntime; if ((this._mergeUnclaimedPreviousCommandResults != PipelineResultTypes.None) && (commandRuntime != null)) { commandRuntime.MergeUnclaimedPreviousErrorResults = true; } if (this._mergeInstructions[0] == PipelineResultTypes.Output) { commandRuntime.ErrorMergeTo = MshCommandRuntime.MergeDataStream.Output; } PipelineResultTypes toType = this._mergeInstructions[1]; if (toType != PipelineResultTypes.None) { commandRuntime.WarningOutputPipe = this.GetRedirectionPipe(toType, commandRuntime); } toType = this._mergeInstructions[2]; if (toType != PipelineResultTypes.None) { commandRuntime.VerboseOutputPipe = this.GetRedirectionPipe(toType, commandRuntime); } toType = this._mergeInstructions[3]; if (toType != PipelineResultTypes.None) { commandRuntime.DebugOutputPipe = this.GetRedirectionPipe(toType, commandRuntime); } }