/// <summary> /// Get suggestion text from suggestion scriptblock with arguments. /// </summary> private static string GetSuggestionText(Object suggestion, object[] suggestionArgs, PSModuleInfo invocationModule) { if (suggestion is ScriptBlock) { ScriptBlock suggestionScript = (ScriptBlock)suggestion; object result = null; try { result = invocationModule.Invoke(suggestionScript, suggestionArgs); } catch (Exception e) { // Catch-all OK. This is a third-party call-out. CommandProcessorBase.CheckForSevereException(e); return(String.Empty); } return((string)LanguagePrimitives.ConvertTo(result, typeof(string), CultureInfo.CurrentCulture)); } else { return((string)LanguagePrimitives.ConvertTo(suggestion, typeof(string), CultureInfo.CurrentCulture)); } }
/// <summary> /// Create a configured remote runspace from provided name. /// </summary> /// <param name="configurationName"></param> /// <param name="host"></param> /// <returns></returns> internal static RemoteRunspace CreateConfiguredRunspace( string configurationName, PSHost host) { // Create a loop-back remote runspace with network access enabled, and // with the provided endpoint configurationname. TypeTable typeTable = TypeTable.LoadDefaultTypeFiles(); var connectInfo = new WSManConnectionInfo(); connectInfo.ShellUri = configurationName.Trim(); connectInfo.EnableNetworkAccess = true; RemoteRunspace remoteRunspace = null; try { remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectInfo, host, typeTable); remoteRunspace.Open(); } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); throw new PSInvalidOperationException( StringUtil.Format(RemotingErrorIdStrings.CannotCreateConfiguredRunspace, configurationName), e); } return(remoteRunspace); }
/// <summary> /// Saves the job to a persisted store. /// </summary> /// <param name="job">Job2 type job to persist</param> /// <param name="definition">Job definition containing source adapter information</param> public void PersistJob(Job2 job, JobDefinition definition) { if (job == null) { throw new PSArgumentNullException("job"); } if (definition == null) { throw new PSArgumentNullException("definition"); } JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition); try { sourceAdapter.PersistJob(job); } 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.NewJob returned unknown error. _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); throw; } }
private Attribute GetCustomAttribute() { Attribute customAttributeObject = this.GetCustomAttributeObject(); if (customAttributeObject != null && this._namedArguments != null) { Hashtable constValue = (Hashtable)this._namedArguments.GetConstValue(); PSObject psObject = LanguagePrimitives.AsPSObjectOrNull((object)customAttributeObject); foreach (object key in (IEnumerable)constValue.Keys) { object obj = constValue[key]; try { PSMemberInfo member = psObject.Members[key.ToString()]; if (member != null) { member.Value = obj; } else { throw InterpreterError.NewInterpreterException((object)this.NodeToken, typeof(RuntimeException), this.NodeToken, "PropertyNotFoundForType", (object)key.ToString(), (object)customAttributeObject.GetType().ToString()); } } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); throw InterpreterError.NewInterpreterExceptionByMessage(typeof(RuntimeException), this.NodeToken, ex.Message, "PropertyAssignmentException", ex); } } } return(customAttributeObject); }
/// <summary> /// Creates a new job of the appropriate type given by JobDefinition passed in. /// </summary> /// <param name="definition">JobDefinition defining the command.</param> /// <returns>Job2 object of the appropriate type specified by the definition.</returns> /// <exception cref="InvalidOperationException">If JobSourceAdapter type specified /// in definition is not registered.</exception> /// <exception cref="Exception">JobSourceAdapter implementation exception thrown on error. /// </exception> public Job2 NewJob(JobDefinition definition) { if (definition == null) { throw new ArgumentNullException("definition"); } JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition); Job2 newJob; #pragma warning disable 56500 try { newJob = sourceAdapter.NewJob(definition); } 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.NewJob returned unknown error. _tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); throw; } #pragma warning restore 56500 return(newJob); }
/// <summary> /// Sets value of this property. /// </summary> /// <param name="target">instance of the object to which to set the property value</param> /// <param name="setValue">value to set this property</param> internal void SetValue(Object target, Object setValue) { object[] propValue = new object[1]; setValue = Adapter.PropertySetAndMethodArgumentConvertTo(setValue, this.Type, CultureInfo.InvariantCulture); propValue[0] = setValue; try { ComInvoker.Invoke(target as IDispatch, _dispId, propValue, null, COM.INVOKEKIND.INVOKE_PROPERTYPUT); } catch (TargetInvocationException te) { //First check if this is a severe exception. CommandProcessorBase.CheckForSevereException(te.InnerException); var innerCom = te.InnerException as COMException; if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } } catch (COMException ce) { if (ce.HResult != ComUtil.DISP_E_UNKNOWNNAME) { throw; } } }
/// <summary> /// Get value of this property /// </summary> /// <param name="target">instance of the object from which to get the property value</param> /// <returns>value of the property</returns> internal object GetValue(Object target) { try { return(ComInvoker.Invoke(target as IDispatch, _dispId, null, null, COM.INVOKEKIND.INVOKE_PROPERTYGET)); } catch (TargetInvocationException te) { //First check if this is a severe exception. CommandProcessorBase.CheckForSevereException(te.InnerException); var innerCom = te.InnerException as COMException; if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } } catch (COMException ce) { if (ce.HResult != ComUtil.DISP_E_UNKNOWNNAME) { throw; } } return(null); }
/// <summary> /// Called once after ProcessRecord(). /// Internally it calls EndProcessing() of the InternalCommand. /// </summary> /// <exception cref="PipelineStoppedException"> /// a terminating error occurred, or the pipeline was otherwise stopped /// </exception> internal virtual void Complete() { // Call ProcessRecord once from complete. Don't call DoExecute... ProcessRecord(); try { using (commandRuntime.AllowThisCommandToWrite(true)) { using (ParameterBinderBase.bindingTracer.TraceScope( "CALLING EndProcessing")) { this.Command.DoEndProcessing(); } } } // 2004/03/18-JonN This is understood to be // an FXCOP violation, cleared by KCwalina. catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); // This cmdlet threw an exception, so // wrap it and bubble it up. throw ManageInvocationException(e); } } // Complete
/// <summary> /// Sets the execution scope for the pipeline and then calls the Prepare /// abstract method which gets overridden by derived classes. /// </summary> internal void DoPrepare(IDictionary psDefaultParameterValues) { CommandProcessorBase oldCurrentCommandProcessor = _context.CurrentCommandProcessor; try { Context.CurrentCommandProcessor = this; SetCurrentScopeToExecutionScope(); Prepare(psDefaultParameterValues); // Check obsolete attribute after Prepare so that -WarningAction will be respected for cmdlets if (ObsoleteAttribute != null) { // Obsolete command is rare. Put the IF here to avoid method call overhead HandleObsoleteCommand(ObsoleteAttribute); } } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); if (_useLocalScope) { // If we had an exception during Prepare, we're done trying to execute the command // so the scope we created needs to release any resources it hold.s CommandSessionState.RemoveScope(CommandScope); } throw; } finally { Context.CurrentCommandProcessor = oldCurrentCommandProcessor; RestorePreviousScope(); } }
} // 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
/// <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); }
} // 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
private void Parse(string script) { try { this._parser.ParseScriptBlock(script, false); } catch (Exception ex) { CommandProcessorBase.CheckForSevereException(ex); } }
} // 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
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(); } } } } }
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 }); } } } }
/// <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
/// <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); } } } } }
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 override void DoStopProcessing() { try { if (this.myCommandProcessor != null) { this.myCommandProcessor.StopProcessing(); } } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } }
private void CleanUp() { try { if (this.nativeProcess != null) { this.nativeProcess.Close(); } } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } }
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); } }
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 ReaderStartProc() { try { this.ReaderStartProcHelper(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } finally { this.processOutputReader.ReaderDone(this.isOutput); } }
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 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... ; } }