private static void WriteMessage(System.Management.Automation.Cmdlet cmdlet, string message) { if (!IsMessageSuppressed) { cmdlet.WriteWarning(message); } }
public VisioPsClientContext(SMA.Cmdlet cmdlet) { this.cmdlet = cmdlet; }
private static IEnumerable <CimModule> GetCimModules( CimSession cimSession, Uri resourceUri, string cimNamespace, string moduleNamePattern, bool onlyManifests, Cmdlet cmdlet, CancellationToken cancellationToken) { Dbg.Assert(cimSession != null, "Caller should verify cimSession != null"); Dbg.Assert(moduleNamePattern != null, "Caller should verify that moduleNamePattern != null"); const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; var wildcardPattern = WildcardPattern.Get(moduleNamePattern, wildcardOptions); string dosWildcard = WildcardPatternToDosWildcardParser.Parse(wildcardPattern); var options = new CimOperationOptions { CancellationToken = cancellationToken }; options.SetCustomOption("PS_ModuleNamePattern", dosWildcard, mustComply: false); if (resourceUri != null) { options.ResourceUri = resourceUri; } if (string.IsNullOrEmpty(cimNamespace) && (resourceUri == null)) { cimNamespace = DiscoveryProviderNamespace; } // TODO/FIXME: ETW for method invocation IEnumerable <CimInstance> syncResults = cimSession.EnumerateInstances( cimNamespace, DiscoveryProviderModuleClass, options); // TODO/FIXME: ETW for method results IEnumerable <CimModule> cimModules = syncResults .Select(cimInstance => new CimModule(cimInstance)) .Where(cimModule => wildcardPattern.IsMatch(cimModule.ModuleName)); if (!onlyManifests) { cimModules = cimModules.Select( (CimModule cimModule) => { cimModule.FetchAllModuleFiles(cimSession, cimNamespace, options); return(cimModule); }); } return(EnumerateWithCatch( cimModules, (Exception exception) => { ErrorRecord errorRecord = GetErrorRecordForRemoteDiscoveryProvider(exception); if (!cmdlet.MyInvocation.ExpectingInput) { if ((errorRecord.FullyQualifiedErrorId.IndexOf(DiscoveryProviderNotFoundErrorId, StringComparison.OrdinalIgnoreCase) != (-1)) || (cancellationToken.IsCancellationRequested || (exception is OperationCanceledException)) || (!cimSession.TestConnection())) { cmdlet.ThrowTerminatingError(errorRecord); } } cmdlet.WriteError(errorRecord); })); }
private void ForwardAllResultsToCmdlet(Cmdlet cmdlet, CancellationToken?cancellationToken) { this.AssertNotDisposed(); ForwardingHelper.ForwardAllResultsToCmdlet(this, cmdlet, cancellationToken); }
public static void ForwardAllResultsToCmdlet(ThrottlingJob throttlingJob, Cmdlet cmdlet, CancellationToken?cancellationToken) { using (var helper = new ForwardingHelper(throttlingJob)) { try { throttlingJob.ChildJobAdded += helper.ThrottlingJob_ChildJobAdded; try { throttlingJob.StateChanged += helper.ThrottlingJob_StateChanged; IDisposable cancellationTokenRegistration = null; if (cancellationToken.HasValue) { cancellationTokenRegistration = cancellationToken.Value.Register(helper.CancelForwarding); } try { Interlocked.MemoryBarrier(); ThreadPool.QueueUserWorkItem( delegate { helper.StartMonitoringJob(throttlingJob); foreach (Job childJob in throttlingJob.GetChildJobsSnapshot()) { helper.StartMonitoringJob(childJob); } helper.CheckIfThrottlingJobIsComplete(); }); helper.ForwardResults(cmdlet); } finally { if (cancellationTokenRegistration != null) { cancellationTokenRegistration.Dispose(); } } } finally { throttlingJob.StateChanged -= helper.ThrottlingJob_StateChanged; } } finally { throttlingJob.ChildJobAdded -= helper.ThrottlingJob_ChildJobAdded; } } }
private Collection <PSObject> InvokeScript(ScriptBlock sb, bool useNewScope, PipelineResultTypes writeToPipeline, IList input, params object[] args) { if (_cmdlet != null) { _cmdlet.ThrowIfStopping(); } Cmdlet cmdletToUse = null; ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe; // Check if they want output if ((writeToPipeline & PipelineResultTypes.Output) == PipelineResultTypes.Output) { cmdletToUse = _cmdlet; writeToPipeline &= (~PipelineResultTypes.Output); } // Check if they want error if ((writeToPipeline & PipelineResultTypes.Error) == PipelineResultTypes.Error) { errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe; writeToPipeline &= (~PipelineResultTypes.Error); } if (writeToPipeline != PipelineResultTypes.None) { // The only output types are Output and Error. throw PSTraceSource.NewNotImplementedException(); } // If the cmdletToUse is not null, then the result of the evaluation will be // streamed out the output pipe of the cmdlet. object rawResult; if (cmdletToUse != null) { sb.InvokeUsingCmdlet( contextCmdlet: cmdletToUse, useLocalScope: useNewScope, errorHandlingBehavior: errorHandlingBehavior, dollarUnder: AutomationNull.Value, input: input, scriptThis: AutomationNull.Value, args: args); rawResult = AutomationNull.Value; } else { rawResult = sb.DoInvokeReturnAsIs( useLocalScope: useNewScope, errorHandlingBehavior: errorHandlingBehavior, dollarUnder: AutomationNull.Value, input: input, scriptThis: AutomationNull.Value, args: args); } if (rawResult == AutomationNull.Value) { return(new Collection <PSObject>()); } // If the result is already a collection of PSObjects, just return it... Collection <PSObject> result = rawResult as Collection <PSObject>; if (result != null) { return(result); } result = new Collection <PSObject>(); IEnumerator list = null; list = LanguagePrimitives.GetEnumerator(rawResult); if (list != null) { while (list.MoveNext()) { object val = list.Current; result.Add(LanguagePrimitives.AsPSObjectOrNull(val)); } } else { result.Add(LanguagePrimitives.AsPSObjectOrNull(rawResult)); } return(result); }
/// <summary> /// Remove a job from the appropriate store. /// </summary> /// <param name="sessionJobId">Session specific Job ID to remove.</param> /// <param name="cmdlet"></param> /// <param name="writeErrorOnException"></param> internal void RemoveJob(int sessionJobId, Cmdlet cmdlet, bool writeErrorOnException) { Job2 job = GetJobById(sessionJobId, cmdlet, writeErrorOnException, false, false); RemoveJob(job, cmdlet, false); }
/// <summary> /// Get job specified by the session specific id provided. /// </summary> /// <param name="id">Session specific job id.</param> /// <param name="cmdlet">Cmdlet requesting this, for error processing.</param> /// <param name="writeErrorOnException"></param> /// <param name="writeObject"></param> /// <param name="recurse"></param> /// <returns>Job that match the specified criteria.</returns> /// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation.</exception> internal Job2 GetJobById(int id, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse) { return(GetJobThroughId <int>(Guid.Empty, id, cmdlet, writeErrorOnException, writeObject, recurse)); }
internal ReflectionParameterBinder(object target, Cmdlet command) : base((object)LanguagePrimitives.AsPSObjectOrNull(target), command.MyInvocation, command.Context, (InternalCommand)command) { using (ReflectionParameterBinder.tracer.TraceConstructor((object)this)) ; }
/// <summary> /// Write a warning message that informs the user that the cmdlet has been migrated from AAD Graph to MS Graph. /// This message applies to those cmdlets that *throw* MSGraph exceptions. /// </summary> internal static void WriteMessageForCmdletsThrowException(System.Management.Automation.Cmdlet cmdlet) => WriteMessage(cmdlet, MessageForCmdletsThrowException);
internal List <Job2> GetJobToStart(string definitionName, string definitionPath, string definitionType, Cmdlet cmdlet, bool writeErrorOnException) { List <Job2> list = new List <Job2>(); WildcardPattern pattern = (definitionType != null) ? new WildcardPattern(definitionType, WildcardOptions.IgnoreCase) : null; lock (this._syncObject) { foreach (JobSourceAdapter adapter in this._sourceAdapters.Values) { try { if (pattern != null) { string adapterName = this.GetAdapterName(adapter); if (!pattern.IsMatch(adapterName)) { continue; } } Job2 item = adapter.NewJob(definitionName, definitionPath); if (item != null) { list.Add(item); } if (pattern != null) { return(list); } } catch (Exception exception) { this.Tracer.TraceException(exception); CommandProcessorBase.CheckForSevereException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", adapter); } } return(list); } return(list); }
internal List <Job2> GetJobsByState(JobState state, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { return(this.GetFilteredJobs(state, FilterType.State, cmdlet, writeErrorOnException, writeObject, recurse, jobSourceAdapterTypes)); }
internal List <Job2> GetJobsByCommand(string command, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { return(this.GetFilteredJobs(command, FilterType.Command, cmdlet, writeErrorOnException, writeObject, recurse, jobSourceAdapterTypes)); }
internal List <Job2> GetJobs(Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, string[] jobSourceAdapterTypes) { return(this.GetFilteredJobs(null, FilterType.None, cmdlet, writeErrorOnException, writeObject, false, jobSourceAdapterTypes)); }
public ErrorDetails(Cmdlet cmdlet, string baseName, string resourceId, params object[] args) { this._message = ""; this._recommendedAction = ""; this._message = this.BuildMessage(cmdlet, baseName, resourceId, args); }
/// <summary> /// Get a filtered list of jobs based on filter type. /// </summary> /// <param name="filter">Object to use for filtering.</param> /// <param name="filterType">Type of filter, specifies which "get" from /// JobSourceAdapter to call, and dictates the type for filter.</param> /// <param name="cmdlet">Cmdlet requesting this, for error processing.</param> /// <param name="writeErrorOnException"></param> /// <param name="writeObject"></param> /// <param name="recurse"></param> /// <param name="jobSourceAdapterTypes">job source adapter type names</param> /// <returns>Filtered list of jobs.</returns> /// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation.</exception> private List <Job2> GetFilteredJobs( object filter, FilterType filterType, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse, string[] jobSourceAdapterTypes) { Diagnostics.Assert(cmdlet != null, "Cmdlet should be passed to JobManager"); List <Job2> allJobs = new List <Job2>(); lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { List <Job2> jobs = null; // Filter search based on job source adapter types if provided. if (!CheckTypeNames(sourceAdapter, jobSourceAdapterTypes)) { continue; } #pragma warning disable 56500 try { jobs = CallJobFilter(sourceAdapter, filter, filterType, 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.GetJobsByFilter() threw unknown exception. _tracer.TraceException(exception); WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobsError", sourceAdapter); } #pragma warning restore 56500 if (jobs == null) { continue; } allJobs.AddRange(jobs); } } if (writeObject) { foreach (Job2 job in allJobs) { cmdlet.WriteObject(job); } } return(allJobs); }
internal ContentCmdletProviderIntrinsics(Cmdlet cmdlet) { _cmdlet = cmdlet; }
/// <summary> /// Get job that has the specified id. /// </summary> /// <param name="instanceId">Guid to match.</param> /// <param name="cmdlet">Cmdlet requesting this, for error processing.</param> /// <param name="writeErrorOnException"></param> /// <param name="writeObject"></param> /// <param name="recurse"></param> /// <returns>Job with the specified guid.</returns> /// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation.</exception> internal Job2 GetJobByInstanceId(Guid instanceId, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse) { return(GetJobThroughId <Guid>(instanceId, 0, cmdlet, writeErrorOnException, writeObject, recurse)); }
internal SecurityDescriptorCmdletProviderIntrinsics(Cmdlet cmdlet) { _cmdlet = cmdlet; }
/// <summary> /// Remove a job from the appropriate store. /// </summary> /// <param name="job">Job object to remove.</param> /// <param name="cmdlet"></param> /// <param name="writeErrorOnException"></param> /// <param name="throwExceptions">If true, will throw all JobSourceAdapter exceptions to caller. /// This is needed if RemoveJob is being called from an event handler in Receive-Job.</param> /// <returns>True if job is found.</returns> internal bool RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, bool throwExceptions = false) { bool jobFound = false; lock (_syncObject) { foreach (JobSourceAdapter sourceAdapter in _sourceAdapters.Values) { Job2 foundJob = null; #pragma warning disable 56500 try { foundJob = sourceAdapter.GetJobByInstanceId(job.InstanceId, true); } 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); if (throwExceptions) { throw; } WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobError", sourceAdapter); } #pragma warning restore 56500 if (foundJob == null) { continue; } jobFound = true; RemoveJobIdForReuse(foundJob); #pragma warning disable 56500 try { sourceAdapter.RemoveJob(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.RemoveJob() threw unknown exception. _tracer.TraceException(exception); if (throwExceptions) { throw; } WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterRemoveJobError", sourceAdapter); } #pragma warning restore 56500 } } if (!jobFound && throwExceptions) { var message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ItemNotFoundInRepository, "Job repository", job.InstanceId.ToString()); throw new ArgumentException(message); } return(jobFound); }
internal ContentCmdletProviderIntrinsics(Cmdlet cmdlet) : base(cmdlet) { }
/// <summary> /// Initializes the command's request object /// </summary> /// <param name="cmdletInformation"> /// The information about the cmdlet. /// </param> /// <exception cref="CmdletInvocationException"> /// If the constructor for the cmdlet threw an exception. /// </exception> /// <exception cref="MemberAccessException"> /// The type referenced by <paramref name="cmdletInformation"/> refered to an /// abstract type or them member was invoked via a late-binding mechanism. /// </exception> /// <exception cref="TypeLoadException"> /// If <paramref name="cmdletInformation"/> refers to a type that is invalid. /// </exception> private void Init(CmdletInfo cmdletInformation) { Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned null."); Cmdlet newCmdlet = null; Exception initError = null; string errorIdAndResourceId = null; string resourceStr = null; try { // Create the request object newCmdlet = ConstructInstance(cmdletInformation.ImplementingType); if (newCmdlet == null) { // We could test the inheritance before constructing, but that's // expensive. Much cheaper to just check for null. initError = new InvalidCastException(); errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType"; resourceStr = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType; } } catch (MemberAccessException memberAccessException) { initError = memberAccessException; } catch (TypeLoadException typeLoadException) { initError = typeLoadException; } catch (Exception e) // Catch-all OK, 3rd party callout. { // We don't have a Command or InvocationInfo at this point, // since the command failed to initialize. var commandException = new CmdletInvocationException(e, null); // Log a command health event MshLog.LogCommandHealthEvent( this._context, commandException, Severity.Warning); throw commandException; } if (initError != null) { // Log a command health event MshLog.LogCommandHealthEvent( this._context, initError, Severity.Warning); CommandNotFoundException exception = new CommandNotFoundException( cmdletInformation.Name, initError, errorIdAndResourceId ?? "CmdletNotFoundException", resourceStr ?? DiscoveryExceptions.CmdletNotFoundException, initError.Message); throw exception; } this.Command = newCmdlet; this.CommandScope = Context.EngineSessionState.CurrentScope; InitCommon(); }
internal ItemCmdletProviderIntrinsics(Cmdlet cmdlet) : base(cmdlet) { }
internal override void ForwardAllResultsToCmdlet(Cmdlet cmdlet) { this.ForwardAllResultsToCmdlet(cmdlet, cancellationToken: null); }
/// <summary> /// Constructs the parameter binder with the specified type metadata. The binder is only valid /// for a single instance of a bindable object and only for the duration of a command. /// </summary> /// <param name="target"> /// The target object that the parameter values will be bound to. /// </param> /// <param name="command"> /// An instance of the command so that attributes can access the context. /// </param> internal ReflectionParameterBinder( object target, Cmdlet command) : base(target, command.MyInvocation, command.Context, command) { }
internal ChildItemCmdletProviderIntrinsics(Cmdlet cmdlet) { this.cmdlet = cmdlet != null ? cmdlet : throw ChildItemCmdletProviderIntrinsics.tracer.NewArgumentNullException(nameof(cmdlet)); this.sessionState = cmdlet.Context.EngineSessionState; }
/// <summary> /// retrieve the encoding parameter from the command line /// it throws if the encoding does not match the known ones /// </summary> /// <returns>a System.Text.Encoding object (null if no encoding specified)</returns> internal static Encoding Convert(Cmdlet cmdlet, string encoding) { if (string.IsNullOrEmpty(encoding)) { // no parameter passed, default to Unicode (OS preferred) return(System.Text.Encoding.Unicode); } // Default to unicode (this matches Get-Content) if (string.Equals(encoding, Unknown, StringComparison.OrdinalIgnoreCase)) { return(System.Text.Encoding.Unicode); } if (string.Equals(encoding, String, StringComparison.OrdinalIgnoreCase)) { return(System.Text.Encoding.Unicode); } // these are the encodings the CLR supports if (string.Equals(encoding, Unicode, StringComparison.OrdinalIgnoreCase)) { return(System.Text.Encoding.Unicode); } if (string.Equals(encoding, BigEndianUnicode, StringComparison.OrdinalIgnoreCase)) { return(System.Text.Encoding.BigEndianUnicode); } if (string.Equals(encoding, Utf8, StringComparison.OrdinalIgnoreCase)) { return(System.Text.Encoding.UTF8); } if (string.Equals(encoding, Ascii, StringComparison.OrdinalIgnoreCase)) { return(System.Text.Encoding.ASCII); } if (string.Equals(encoding, Utf7, StringComparison.OrdinalIgnoreCase)) { return(System.Text.Encoding.UTF7); } if (string.Equals(encoding, Utf32, StringComparison.OrdinalIgnoreCase)) { return(System.Text.Encoding.UTF32); } if (string.Equals(encoding, Default, StringComparison.OrdinalIgnoreCase)) { return(ClrFacade.GetDefaultEncoding()); } if (string.Equals(encoding, OEM, StringComparison.OrdinalIgnoreCase)) { return(ClrFacade.GetOEMEncoding()); } // error condition: unknown encoding value string validEncodingValues = string.Join( ", ", new string[] { Unknown, String, Unicode, BigEndianUnicode, Ascii, Utf8, Utf7, Utf32, Default, OEM }); string msg = StringUtil.Format(PathUtilsStrings.OutFile_WriteToFileEncodingUnknown, encoding, validEncodingValues); ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentException("Encoding"), "WriteToFileEncodingUnknown", ErrorCategory.InvalidArgument, null); errorRecord.ErrorDetails = new ErrorDetails(msg); cmdlet.ThrowTerminatingError(errorRecord); return(null); }
internal ItemCmdletProviderIntrinsics(Cmdlet cmdlet) { _cmdlet = cmdlet; }
/// <summary> /// Get list of jobs based on the adapter specific /// filter parameters. /// </summary> /// <param name="filter">Dictionary containing name value /// pairs for adapter specific filters.</param> /// <param name="cmdlet">Cmdlet requesting this, for error processing.</param> /// <param name="writeErrorOnException"></param> /// <param name="writeObject"></param> /// <param name="recurse"></param> /// <returns>Collection of jobs that match the /// specified criteria.</returns> /// <exception cref="Exception">If cmdlet parameter is null, throws exception on error from /// JobSourceAdapter implementation.</exception> internal List <Job2> GetJobsByFilter(Dictionary <string, object> filter, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse) { return(GetFilteredJobs(filter, FilterType.Filter, cmdlet, writeErrorOnException, writeObject, recurse, null)); }
public VisioPsContext(SMA.Cmdlet cmdlet) { this.cmdlet = cmdlet; }
internal PropertyCmdletProviderIntrinsics(Cmdlet cmdlet) { _cmdlet = cmdlet; }