// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Security; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace System.Management.Automation.Internal { /// /// Serves as the base class for Metadata attributes. /// /// /// PSSnapins may not create custom attributes derived directly from , /// since it has no public constructor. Only the public subclasses /// and are available. /// /// /// /// [AttributeUsage(AttributeTargets.All)] public abstract class CmdletMetadataAttribute : Attribute { /// /// Default constructor. /// internal CmdletMetadataAttribute() { } } /// /// Serves as the base class for Metadata attributes that serve as guidance to the parser and parameter binder. /// /// /// PSSnapins may not create custom attributes derived from , since it /// has no public constructor. Only the sealed public subclasses and /// are available. /// /// /// /// [AttributeUsage(AttributeTargets.All)] public abstract class ParsingBaseAttribute : CmdletMetadataAttribute { /// /// Constructor with no parameters. /// internal ParsingBaseAttribute() { } } } namespace System.Management.Automation { #region Base Metadata Classes /// /// Serves as the base class for Validate attributes that validate parameter arguments. /// /// /// Argument validation attributes can be attached to and /// parameters to ensure that the Cmdlet or CmdletProvider will /// not be invoked with invalid values of the parameter. Existing validation attributes include /// , /// , /// , /// , /// , /// , /// , and /// . /// PSSnapins wishing to create custom argument validation attributes should derive from /// and override the /// abstract method, after which they can apply the /// attribute to their parameters. /// validates the argument as a whole. If the argument value may /// be an enumerable, you can derive from /// which will take care of unrolling the enumerable and validate each element individually. /// It is also recommended to override to return a readable string /// similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]". /// If this attribute is applied to a string parameter, the string command argument will be validated. /// If this attribute is applied to a string[] parameter, the string[] command argument will be validated. /// /// /// /// /// /// /// /// /// /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public abstract class ValidateArgumentsAttribute : CmdletMetadataAttribute { /// /// Verify that the value of is valid. /// /// Argument value to validate. /// /// The engine APIs for the context under which the prerequisite is being evaluated. /// /// Should be thrown for any validation failure. protected abstract void Validate(object arguments, EngineIntrinsics engineIntrinsics); /// /// Method that the command processor calls for data validate processing. /// /// Object to validate. /// /// The engine APIs for the context under which the prerequisite is being evaluated. /// /// True if the validation succeeded. /// /// Whenever any exception occurs during data validation. /// Additionally, all the system exceptions are wrapped in ValidationMetadataException. /// /// For invalid arguments. internal void InternalValidate(object o, EngineIntrinsics engineIntrinsics) => Validate(o, engineIntrinsics); /// /// Initializes a new instance of a class derived from . /// protected ValidateArgumentsAttribute() { } } /// /// A variant of which unrolls enumeration values and validates /// each element individually. /// /// /// is like , /// except that if the argument value is enumerable, /// will unroll the enumeration and validate each item individually. /// Existing enumerated validation attributes include /// , /// , /// , and /// . /// PSSnapins wishing to create custom enumerated argument validation attributes should derive from /// and override the /// /// abstract method, after which they can apply the attribute to their parameters. /// It is also recommended to override to return a readable string /// similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]". /// If this attribute is applied to a string parameter, the string command argument will be validated. /// If this attribute is applied to a string[] parameter, each string command argument will be validated. /// /// /// /// /// /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public abstract class ValidateEnumeratedArgumentsAttribute : ValidateArgumentsAttribute { /// /// Initializes a new instance of a class derived from . /// protected ValidateEnumeratedArgumentsAttribute() : base() { } /// /// Abstract method to be overridden by subclasses, implementing the validation of each parameter argument. /// /// /// Validate that the value of is valid, and throw /// if it is invalid. /// /// One of the parameter arguments. /// Should be thrown for any validation failure. protected abstract void ValidateElement(object element); /// /// Calls ValidateElement in each element in the enumeration argument value. /// /// Object to validate. /// /// The engine APIs for the context under which the prerequisite is being evaluated. /// /// /// PSSnapins should override instead. /// /// Should be thrown for any validation failure. protected sealed override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (LanguagePrimitives.IsNull(arguments)) { throw new ValidationMetadataException( "ArgumentIsEmpty", null, Metadata.ValidateNotNullOrEmptyCollectionFailure); } var enumerator = _getEnumeratorSite.Target.Invoke(_getEnumeratorSite, arguments); if (enumerator == null) { ValidateElement(arguments); return; } // arguments is IEnumerator while (enumerator.MoveNext()) { ValidateElement(enumerator.Current); } enumerator.Reset(); } private readonly CallSite> _getEnumeratorSite = CallSite>.Create(PSEnumerableBinder.Get()); } #endregion Base Metadata Classes #region Misc Attributes /// /// To specify RunAs behavior for the class /// /// public enum DSCResourceRunAsCredential { /// Default is same as optional. Default, /// /// PsDscRunAsCredential can not be used for this DSC Resource. /// NotSupported, /// /// PsDscRunAsCredential is mandatory for resource. /// Mandatory, /// /// PsDscRunAsCredential can or can not be specified. /// Optional = Default, } /// /// Indicates the class defines a DSC resource. /// [AttributeUsage(AttributeTargets.Class)] public class DscResourceAttribute : CmdletMetadataAttribute { /// /// To specify RunAs Behavior for the resource. /// public DSCResourceRunAsCredential RunAsCredential { get; set; } } /// /// When specified on a property or field of a DSC Resource, the property /// can or must be specified in a configuration, unless it is marked /// , in which case it is /// returned by the Get() method of the resource. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class DscPropertyAttribute : CmdletMetadataAttribute { /// /// Indicates the property is a required key property for a DSC resource. /// public bool Key { get; set; } /// /// Indicates the property is a required property for a DSC resource. /// public bool Mandatory { get; set; } /// /// Indicates the property is not a parameter to the DSC resource, but the /// property will contain a value after the Get() method of the resource is called. /// public bool NotConfigurable { get; set; } } /// /// Indication the configuration is for local configuration manager, also known as meta configuration. /// [AttributeUsage(AttributeTargets.Class)] public class DscLocalConfigurationManagerAttribute : CmdletMetadataAttribute { } /// /// Contains information about a cmdlet's metadata. /// [AttributeUsage(AttributeTargets.Class)] public abstract class CmdletCommonMetadataAttribute : CmdletMetadataAttribute { /// /// Gets or sets the cmdlet default parameter set. /// public string DefaultParameterSetName { get; set; } /// /// Gets or sets a Boolean value that indicates the Cmdlet supports ShouldProcess. By default /// the value is false, meaning the cmdlet doesn't support ShouldProcess. /// public bool SupportsShouldProcess { get; set; } = false; /// /// Gets or sets a Boolean value that indicates the Cmdlet supports Paging. By default /// the value is false, meaning the cmdlet doesn't support Paging. /// public bool SupportsPaging { get; set; } = false; /// /// Gets or sets a Boolean value that indicates the Cmdlet supports Transactions. By default /// the value is false, meaning the cmdlet doesn't support Transactions. /// public bool SupportsTransactions { get { return _supportsTransactions; } set { #if !CORECLR _supportsTransactions = value; #else // Disable 'SupportsTransactions' in CoreCLR // No transaction supported on CSS due to the lack of System.Transactions namespace _supportsTransactions = false; #endif } } private bool _supportsTransactions = false; private ConfirmImpact _confirmImpact = ConfirmImpact.Medium; /// /// Gets or sets a ConfirmImpact value that indicates the "destructiveness" of the operation /// and when it should be confirmed. This should only be used when SupportsShouldProcess is /// specified. /// public ConfirmImpact ConfirmImpact { get => SupportsShouldProcess ? _confirmImpact : ConfirmImpact.None; set => _confirmImpact = value; } /// /// Gets or sets a HelpUri value that indicates the location of online help. This is used by /// Get-Help to retrieve help content when -Online is specified. /// [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] public string HelpUri { get; set; } = string.Empty; /// /// Gets or sets the RemotingBehavior value that declares how this cmdlet should interact /// with ambient remoting. /// public RemotingCapability RemotingCapability { get; set; } = RemotingCapability.PowerShell; } /// /// Identifies a class as a cmdlet and specifies the verb and noun identifying this cmdlet. /// [AttributeUsage(AttributeTargets.Class)] public sealed class CmdletAttribute : CmdletCommonMetadataAttribute { /// /// Gets the cmdlet noun. /// public string NounName { get; } /// /// Gets the cmdlet verb. /// public string VerbName { get; } /// /// Initializes a new instance of the CmdletAttribute class. /// /// Verb for the command. /// Noun for the command. /// For invalid arguments. public CmdletAttribute(string verbName, string nounName) { // NounName,VerbName have to be Non-Null strings if (string.IsNullOrEmpty(nounName)) { throw PSTraceSource.NewArgumentException(nameof(nounName)); } if (string.IsNullOrEmpty(verbName)) { throw PSTraceSource.NewArgumentException(nameof(verbName)); } NounName = nounName; VerbName = verbName; } } /// /// Identifies PowerShell script code as behaving like a cmdlet and hence uses cmdlet parameter binding /// instead of script parameter binding. /// [AttributeUsage(AttributeTargets.Class)] public class CmdletBindingAttribute : CmdletCommonMetadataAttribute { /// /// When true, the script will auto-generate appropriate parameter metadata to support positional /// parameters if the script hasn't already specified multiple parameter sets or specified positions /// explicitly via the . /// public bool PositionalBinding { get; set; } = true; } /// /// OutputTypeAttribute is used to specify the type of objects output by a cmdlet or script. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")] public sealed class OutputTypeAttribute : CmdletMetadataAttribute { /// /// Construct the attribute from a System.Type /// internal OutputTypeAttribute(Type type) { Type = new[] { new PSTypeName(type) }; } /// /// Construct the attribute from a type name. /// internal OutputTypeAttribute(string typeName) { Type = new[] { new PSTypeName(typeName) }; } /// /// Construct the attribute from an array of System.Type /// /// The types output by the cmdlet. public OutputTypeAttribute(params Type[] type) { if (type?.Length > 0) { Type = new PSTypeName[type.Length]; for (int i = 0; i < type.Length; i++) { Type[i] = new PSTypeName(type[i]); } } else { Type = Array.Empty(); } } /// /// Construct the attribute from an array of names of types. /// /// The types output by the cmdlet. public OutputTypeAttribute(params string[] type) { if (type?.Length > 0) { Type = new PSTypeName[type.Length]; for (int i = 0; i < type.Length; i++) { Type[i] = new PSTypeName(type[i]); } } else { Type = Array.Empty(); } } /// /// The types specified by the attribute. /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public PSTypeName[] Type { get; } /// /// Attributes implemented by a provider can use: /// [OutputType(ProviderCmdlet='cmdlet', typeof(...))] /// To specify the provider specific objects returned for a given cmdlet. /// public string ProviderCmdlet { get; set; } /// /// The list of parameter sets this OutputType specifies. /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ParameterSetName { get => _parameterSetName ??= new[] { ParameterAttribute.AllParameterSets }; set => _parameterSetName = value; } private string[] _parameterSetName; } /// /// This attribute is used on a dynamic assembly to mark it as one that is used to implement /// a set of classes defined in a PowerShell script. /// [AttributeUsage(AttributeTargets.Assembly)] public class DynamicClassImplementationAssemblyAttribute : Attribute { /// /// The (possibly null) path to the file defining this class. /// public string ScriptFile { get; set; } } #endregion Misc Attributes #region Parsing guidelines Attributes /// /// Declares an alternative name for a parameter, cmdlet, or function. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] public sealed class AliasAttribute : ParsingBaseAttribute { internal string[] aliasNames; /// /// Gets the alias names passed to the constructor. /// public IList AliasNames { get => this.aliasNames; } /// /// Initializes a new instance of the AliasAttribute class. /// /// The name for this alias. /// For invalid arguments. public AliasAttribute(params string[] aliasNames) { if (aliasNames == null) { throw PSTraceSource.NewArgumentNullException(nameof(aliasNames)); } this.aliasNames = aliasNames; } } /// /// Identifies parameters to Cmdlets. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class ParameterAttribute : ParsingBaseAttribute { /// /// ParameterSetName referring to all ParameterSets. /// public const string AllParameterSets = "__AllParameterSets"; /// /// Initializes a new instance of the ParameterAttribute class. /// public ParameterAttribute() { } /// /// Initializes a new instance that is associated with an experimental feature. /// public ParameterAttribute(string experimentName, ExperimentAction experimentAction) { ExperimentalAttribute.ValidateArguments(experimentName, experimentAction); ExperimentName = experimentName; ExperimentAction = experimentAction; } private string _parameterSetName = ParameterAttribute.AllParameterSets; private string _helpMessage; private string _helpMessageBaseName; private string _helpMessageResourceId; #region Experimental Feature Related Properties /// /// Gets the name of the experimental feature this attribute is associated with. /// public string ExperimentName { get; } /// /// Gets the action for the engine to take when the experimental feature is enabled. /// public ExperimentAction ExperimentAction { get; } internal bool ToHide => EffectiveAction == ExperimentAction.Hide; internal bool ToShow => EffectiveAction == ExperimentAction.Show; /// /// Gets the effective action to take at run time. /// private ExperimentAction EffectiveAction { get { if (_effectiveAction == ExperimentAction.None) { _effectiveAction = ExperimentalFeature.GetActionToTake(ExperimentName, ExperimentAction); } return _effectiveAction; } } private ExperimentAction _effectiveAction = default(ExperimentAction); #endregion /// /// Gets or sets the parameter position. /// If not set, the parameter is named. /// public int Position { get; set; } = int.MinValue; /// /// Gets or sets the name of the parameter set this parameter belongs to. /// When it is not specified, is assumed. /// public string ParameterSetName { get => _parameterSetName; set => _parameterSetName = string.IsNullOrEmpty(value) ? ParameterAttribute.AllParameterSets : value; } /// /// Gets or sets a flag specifying if this parameter is Mandatory. /// When it is not specified, false is assumed and the parameter is considered optional. /// public bool Mandatory { get; set; } = false; /// /// Gets or sets a flag that specifies that this parameter can take values from the incoming pipeline /// object. /// When it is not specified, false is assumed. /// public bool ValueFromPipeline { get; set; } /// /// Gets or sets a flag that specifies that this parameter can take values from a property in the /// incoming pipeline object with the same name as the parameter or an alias of the parameter. /// When it is not specified, false is assumed. /// public bool ValueFromPipelineByPropertyName { get; set; } /// /// Gets or sets a flag that specifies that the remaining command line parameters should be /// associated with this parameter in the form of an array. /// When it is not specified, false is assumed. /// public bool ValueFromRemainingArguments { get; set; } = false; /// /// Gets or sets a short description for this parameter, suitable for presentation as a tool tip. /// /// For a null or empty value when setting. public string HelpMessage { get => _helpMessage; set { if (string.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException(nameof(HelpMessage)); } _helpMessage = value; } } /// /// Gets or sets the base name of the resource for a help message. /// When this field is specified, HelpMessageResourceId must also be specified. /// /// For a null or empty value when setting. public string HelpMessageBaseName { get => _helpMessageBaseName; set { if (string.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException(nameof(HelpMessageBaseName)); } _helpMessageBaseName = value; } } /// /// Gets or sets the Id of the resource for a help message. /// When this field is specified, HelpMessageBaseName must also be specified. /// /// For a null or empty value when setting. public string HelpMessageResourceId { get => _helpMessageResourceId; set { if (string.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentException(nameof(HelpMessageResourceId)); } _helpMessageResourceId = value; } } /// /// Indicates that this parameter should not be shown to the user in this like intellisense /// This is primarily to be used in functions that are implementing the logic for dynamic keywords. /// public bool DontShow { get; set; } } /// /// Specifies PSTypeName of a cmdlet or function parameter. /// /// /// This attribute is used to restrict the type name of the parameter, when the type goes beyond the .NET type system. /// For example one could say: [PSTypeName("System.Management.ManagementObject#root\cimv2\Win32_Process")] /// to only allow Win32_Process objects to be bound to the parameter. /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class PSTypeNameAttribute : Attribute { /// /// public string PSTypeName { get; } /// /// Creates a new PSTypeNameAttribute. /// /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public PSTypeNameAttribute(string psTypeName) { if (string.IsNullOrEmpty(psTypeName)) { throw PSTraceSource.NewArgumentException(nameof(psTypeName)); } this.PSTypeName = psTypeName; } } /// /// Specifies that a parameter supports wildcards. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class SupportsWildcardsAttribute : ParsingBaseAttribute { } /// /// Specify a default value and/or help comment for a command parameter. This attribute /// does not have any semantic meaning, it is simply an aid to tools to make it simpler /// to know the true default value of a command parameter (which may or may not have /// any correlation with, e.g., the backing store of the Parameter's property or field. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class PSDefaultValueAttribute : ParsingBaseAttribute { /// /// Specify the default value of a command parameter. The PowerShell engine does not /// use this value in any way, it exists for other tools that want to reflect on cmdlets. /// public object Value { get; set; } /// /// Specify the help string for the default value of a command parameter. /// public string Help { get; set; } } /// /// Specify that the member is hidden for the purposes of cmdlets like Get-Member and that the /// member is not displayed by default by Format-* cmdlets. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Event)] public sealed class HiddenAttribute : ParsingBaseAttribute { } #endregion Parsing guidelines Attributes #region Data validate Attributes /// /// Validates that the length of each parameter argument's Length falls in the range specified by /// and . /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidateLengthAttribute : ValidateEnumeratedArgumentsAttribute { /// /// Gets the attribute's minimum length. /// public int MinLength { get; } /// /// Gets the attribute's maximum length. /// public int MaxLength { get; } /// /// Validates that the length of each parameter argument's Length falls in the range specified /// by and . /// /// Object to validate. /// If is not a string /// with length between minLength and maxLength /// For invalid arguments. protected override void ValidateElement(object element) { if (element is not string objectString) { throw new ValidationMetadataException( "ValidateLengthNotString", null, Metadata.ValidateLengthNotString); } int len = objectString.Length; if (len < MinLength) { throw new ValidationMetadataException( "ValidateLengthMinLengthFailure", null, Metadata.ValidateLengthMinLengthFailure, MinLength, len); } if (len > MaxLength) { throw new ValidationMetadataException( "ValidateLengthMaxLengthFailure", null, Metadata.ValidateLengthMaxLengthFailure, MaxLength, len); } } /// /// Initializes a new instance of the class. /// /// Minimum required length. /// Maximum required length. /// For invalid arguments. /// If maxLength is less than minLength. public ValidateLengthAttribute(int minLength, int maxLength) : base() { if (minLength < 0) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(minLength), minLength); } if (maxLength <= 0) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxLength), maxLength); } if (maxLength < minLength) { throw new ValidationMetadataException( "ValidateLengthMaxLengthSmallerThanMinLength", null, Metadata.ValidateLengthMaxLengthSmallerThanMinLength); } MinLength = minLength; MaxLength = maxLength; } } /// /// Predefined range kind to use with ValidateRangeAttribute. /// public enum ValidateRangeKind { /// /// Range is greater than 0. /// Positive, /// /// Range is greater than or equal to 0. /// NonNegative, /// /// Range is less than 0. /// Negative, /// /// Range is less than or equal to 0. /// NonPositive } /// /// Validates that each parameter argument falls in the range specified by /// and . /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidateRangeAttribute : ValidateEnumeratedArgumentsAttribute { /// /// Gets the attribute's minimum range. /// public object MinRange { get; } private readonly IComparable _minComparable; /// /// Gets the attribute's maximum range. /// public object MaxRange { get; } private readonly IComparable _maxComparable; /// /// The range values and the value to validate will all be converted to the promoted type. /// If minRange and maxRange are the same type, /// private readonly Type _promotedType; /// /// Gets the name of the predefined range. /// internal ValidateRangeKind? RangeKind { get => _rangeKind; } private readonly ValidateRangeKind? _rangeKind; /// /// Validates that each parameter argument falls in the range specified by /// and . /// /// Object to validate. /// /// Thrown if the object to be validated does not implement , /// if the element type is not the same as MinRange/MaxRange, or if the element is not between /// MinRange and MaxRange. /// protected override void ValidateElement(object element) { if (element == null) { throw new ValidationMetadataException( "ArgumentIsEmpty", null, Metadata.ValidateNotNullFailure); } var o = element as PSObject; if (o != null) { element = o.BaseObject; } if (_rangeKind.HasValue) { ValidateRange(element, (ValidateRangeKind)_rangeKind); } else { ValidateRange(element); } } /// /// Initializes a new instance of the class. /// /// Minimum value of the range allowed. /// Maximum value of the range allowed. /// For invalid arguments. /// /// if has a different type than /// if is smaller than /// if , are not /// public ValidateRangeAttribute(object minRange, object maxRange) : base() { if (minRange == null) { throw PSTraceSource.NewArgumentNullException(nameof(minRange)); } if (maxRange == null) { throw PSTraceSource.NewArgumentNullException(nameof(maxRange)); } if (maxRange.GetType() != minRange.GetType()) { bool failure = true; _promotedType = GetCommonType(minRange.GetType(), maxRange.GetType()); if (_promotedType != null) { if (LanguagePrimitives.TryConvertTo(minRange, _promotedType, out object minResultValue) && LanguagePrimitives.TryConvertTo(maxRange, _promotedType, out object maxResultValue)) { minRange = minResultValue; maxRange = maxResultValue; failure = false; } } if (failure) { throw new ValidationMetadataException( "MinRangeNotTheSameTypeOfMaxRange", null, Metadata.ValidateRangeMinRangeMaxRangeType, minRange.GetType().Name, maxRange.GetType().Name); } } else { _promotedType = minRange.GetType(); } // minRange and maxRange have the same type, so we just need to check one of them _minComparable = minRange as IComparable; if (_minComparable == null) { throw new ValidationMetadataException( "MinRangeNotIComparable", null, Metadata.ValidateRangeNotIComparable); } _maxComparable = maxRange as IComparable; Diagnostics.Assert(_maxComparable != null, "maxComparable comes from a type that is IComparable"); // Thanks to the IComparable test above this will not throw. They have the same type and are IComparable. if (_minComparable.CompareTo(maxRange) > 0) { throw new ValidationMetadataException( "MaxRangeSmallerThanMinRange", null, Metadata.ValidateRangeMaxRangeSmallerThanMinRange); } MinRange = minRange; MaxRange = maxRange; } /// /// Initializes a new instance of the class. /// This constructor uses a predefined . /// public ValidateRangeAttribute(ValidateRangeKind kind) : base() { _rangeKind = kind; } private static void ValidateRange(object element, ValidateRangeKind rangeKind) { if (element is TimeSpan ts) { ValidateTimeSpanRange(ts, rangeKind); return; } Type commonType = GetCommonType(typeof(int), element.GetType()); if (commonType == null) { throw new ValidationMetadataException( "ValidationRangeElementType", innerException: null, Metadata.ValidateRangeElementType, element.GetType().Name, nameof(Int32)); } object resultValue; IComparable dynamicZero = 0; if (LanguagePrimitives.TryConvertTo(element, commonType, out resultValue)) { element = resultValue; if (LanguagePrimitives.TryConvertTo(0, commonType, out resultValue)) { dynamicZero = (IComparable)resultValue; } } else { throw new ValidationMetadataException( "ValidationRangeElementType", null, Metadata.ValidateRangeElementType, element.GetType().Name, commonType.Name); } switch (rangeKind) { case ValidateRangeKind.Positive: if (dynamicZero.CompareTo(element) >= 0) { throw new ValidationMetadataException( "ValidateRangePositiveFailure", null, Metadata.ValidateRangePositiveFailure, element.ToString()); } break; case ValidateRangeKind.NonNegative: if (dynamicZero.CompareTo(element) > 0) { throw new ValidationMetadataException( "ValidateRangeNonNegativeFailure", null, Metadata.ValidateRangeNonNegativeFailure, element.ToString()); } break; case ValidateRangeKind.Negative: if (dynamicZero.CompareTo(element) <= 0) { throw new ValidationMetadataException( "ValidateRangeNegativeFailure", null, Metadata.ValidateRangeNegativeFailure, element.ToString()); } break; case ValidateRangeKind.NonPositive: if (dynamicZero.CompareTo(element) < 0) { throw new ValidationMetadataException( "ValidateRangeNonPositiveFailure", null, Metadata.ValidateRangeNonPositiveFailure, element.ToString()); } break; } } private void ValidateRange(object element) { // MinRange and MaxRange have the same type, so we just need to compare to one of them. if (element.GetType() != _promotedType) { if (LanguagePrimitives.TryConvertTo(element, _promotedType, out object resultValue)) { element = resultValue; } else { throw new ValidationMetadataException( "ValidationRangeElementType", null, Metadata.ValidateRangeElementType, element.GetType().Name, MinRange.GetType().Name); } } // They are the same type and are all IComparable, so this should not throw if (_minComparable.CompareTo(element) > 0) { throw new ValidationMetadataException( "ValidateRangeTooSmall", null, Metadata.ValidateRangeSmallerThanMinRangeFailure, element.ToString(), MinRange.ToString()); } if (_maxComparable.CompareTo(element) < 0) { throw new ValidationMetadataException( "ValidateRangeTooBig", null, Metadata.ValidateRangeGreaterThanMaxRangeFailure, element.ToString(), MaxRange.ToString()); } } private static void ValidateTimeSpanRange(TimeSpan element, ValidateRangeKind rangeKind) { TimeSpan zero = TimeSpan.Zero; switch (rangeKind) { case ValidateRangeKind.Positive: if (zero.CompareTo(element) >= 0) { throw new ValidationMetadataException( "ValidateRangePositiveFailure", null, Metadata.ValidateRangePositiveFailure, element.ToString()); } break; case ValidateRangeKind.NonNegative: if (zero.CompareTo(element) > 0) { throw new ValidationMetadataException( "ValidateRangeNonNegativeFailure", null, Metadata.ValidateRangeNonNegativeFailure, element.ToString()); } break; case ValidateRangeKind.Negative: if (zero.CompareTo(element) <= 0) { throw new ValidationMetadataException( "ValidateRangeNegativeFailure", null, Metadata.ValidateRangeNegativeFailure, element.ToString()); } break; case ValidateRangeKind.NonPositive: if (zero.CompareTo(element) < 0) { throw new ValidationMetadataException( "ValidateRangeNonPositiveFailure", null, Metadata.ValidateRangeNonPositiveFailure, element.ToString()); } break; } } private static Type GetCommonType(Type minType, Type maxType) { Type resultType = null; TypeCode minTypeCode = LanguagePrimitives.GetTypeCode(minType); TypeCode maxTypeCode = LanguagePrimitives.GetTypeCode(maxType); TypeCode opTypeCode = (int)minTypeCode >= (int)maxTypeCode ? minTypeCode : maxTypeCode; if ((int)opTypeCode <= (int)TypeCode.Int32) { resultType = typeof(int); } else if ((int)opTypeCode <= (int)TypeCode.UInt32) { // If one of the operands is signed, we need to promote to double if the value is negative. // We aren't checking the value, so we unconditionally promote to double. resultType = LanguagePrimitives.IsSignedInteger(minTypeCode) || LanguagePrimitives.IsSignedInteger(maxTypeCode) ? typeof(double) : typeof(uint); } else if ((int)opTypeCode <= (int)TypeCode.Int64) { resultType = typeof(long); } else if ((int)opTypeCode <= (int)TypeCode.UInt64) { // If one of the operands is signed, we need to promote to double if the value is negative. // We aren't checking the value, so we unconditionally promote to double. resultType = LanguagePrimitives.IsSignedInteger(minTypeCode) || LanguagePrimitives.IsSignedInteger(maxTypeCode) ? typeof(double) : typeof(ulong); } else if (opTypeCode == TypeCode.Decimal) { resultType = typeof(decimal); } else if (opTypeCode == TypeCode.Single || opTypeCode == TypeCode.Double) { resultType = typeof(double); } return resultType; } /// /// Returns only the elements that passed the attribute's validation. /// /// The objects to validate. internal IEnumerable GetValidatedElements(IEnumerable elementsToValidate) { foreach (var el in elementsToValidate) { try { ValidateElement(el); } catch (ValidationMetadataException) { // Element was not in range - drop continue; } yield return el; } } } /// /// Validates that each parameter argument matches the . /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidatePatternAttribute : ValidateEnumeratedArgumentsAttribute { /// /// Gets the Regex pattern to be used in the validation. /// public string RegexPattern { get; } /// /// Gets or sets the Regex options to be used in the validation. /// public RegexOptions Options { get; set; } = RegexOptions.IgnoreCase; /// /// Gets or sets the custom error message pattern that is displayed to the user. /// The text representation of the object being validated and the validating regex is passed as /// the first and second formatting parameters to the ErrorMessage formatting pattern. /// /// /// [ValidatePattern("\s+", ErrorMessage="The text '{0}' did not pass validation of regex '{1}'")] /// /// /// public string ErrorMessage { get; set; } /// /// Validates that each parameter argument matches the RegexPattern. /// /// Object to validate. /// /// If is not a string that matches the pattern, and for invalid arguments. /// protected override void ValidateElement(object element) { if (element == null) { throw new ValidationMetadataException( "ArgumentIsEmpty", null, Metadata.ValidateNotNullFailure); } string objectString = element.ToString(); var regex = new Regex(RegexPattern, Options); Match match = regex.Match(objectString); if (!match.Success) { var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage) ? Metadata.ValidatePatternFailure : ErrorMessage; throw new ValidationMetadataException( "ValidatePatternFailure", null, errorMessageFormat, objectString, RegexPattern); } } /// /// Initializes a new instance of the class. /// /// Pattern string to match. /// For invalid arguments. public ValidatePatternAttribute(string regexPattern) { if (string.IsNullOrEmpty(regexPattern)) { throw PSTraceSource.NewArgumentException(nameof(regexPattern)); } RegexPattern = regexPattern; } } /// /// Class for validating against a script block. /// public sealed class ValidateScriptAttribute : ValidateEnumeratedArgumentsAttribute { /// /// Gets or sets the custom error message that is displayed to the user. /// The item being validated and the validating scriptblock is passed as the first and second /// formatting argument. /// /// /// [ValidateScript("$_ % 2", ErrorMessage = "The item '{0}' did not pass validation of script '{1}'")] /// /// /// public string ErrorMessage { get; set; } /// /// Gets the scriptblock to be used in the validation. /// public ScriptBlock ScriptBlock { get; } /// /// Validates that each parameter argument matches the scriptblock. /// /// Object to validate. /// If is invalid. protected override void ValidateElement(object element) { if (element == null) { throw new ValidationMetadataException( "ArgumentIsEmpty", null, Metadata.ValidateNotNullFailure); } object result = ScriptBlock.DoInvokeReturnAsIs( useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, dollarUnder: LanguagePrimitives.AsPSObjectOrNull(element), input: AutomationNull.Value, scriptThis: AutomationNull.Value, args: Array.Empty()); if (!LanguagePrimitives.IsTrue(result)) { var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage) ? Metadata.ValidateScriptFailure : ErrorMessage; throw new ValidationMetadataException( "ValidateScriptFailure", null, errorMessageFormat, element, ScriptBlock); } } /// /// Initializes a new instance of the class. /// /// Scriptblock to match. /// For invalid arguments. public ValidateScriptAttribute(ScriptBlock scriptBlock) { if (scriptBlock == null) { throw PSTraceSource.NewArgumentException(nameof(scriptBlock)); } ScriptBlock = scriptBlock; } } /// /// Validates that the parameter argument count is in the specified range. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidateCountAttribute : ValidateArgumentsAttribute { /// /// Gets the minimum length of this attribute. /// public int MinLength { get; } /// /// Gets the maximum length of this attribute. /// public int MaxLength { get; } /// /// Validates that the parameter argument count is in the specified range. /// /// Object to validate. /// /// The engine APIs for the context under which the validation is being evaluated. /// /// /// if the element is none of , , /// , /// if the element's length is not between and /// protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { int len = 0; if (arguments == null || arguments == AutomationNull.Value) { // treat a nul list the same as an empty list // with a count of zero. len = 0; } else if (arguments is IList il) { len = il.Count; } else if (arguments is ICollection ic) { len = ic.Count; } else if (arguments is IEnumerable ie) { IEnumerator e = ie.GetEnumerator(); while (e.MoveNext()) { len++; } } else if (arguments is IEnumerator enumerator) { while (enumerator.MoveNext()) { len++; } } else { // No conversion succeeded so throw an exception... throw new ValidationMetadataException( "NotAnArrayParameter", null, Metadata.ValidateCountNotInArray); } if (MinLength == MaxLength && len != MaxLength) { throw new ValidationMetadataException( "ValidateCountExactFailure", null, Metadata.ValidateCountExactFailure, MaxLength, len); } if (len < MinLength || len > MaxLength) { throw new ValidationMetadataException( "ValidateCountMinMaxFailure", null, Metadata.ValidateCountMinMaxFailure, MinLength, MaxLength, len); } } /// /// Initializes a new instance of the class. /// /// Minimum number of values required. /// Maximum number of values required. /// For invalid arguments. /// /// if is greater than /// public ValidateCountAttribute(int minLength, int maxLength) { if (minLength < 0) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(minLength), minLength); } if (maxLength <= 0) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxLength), maxLength); } if (maxLength < minLength) { throw new ValidationMetadataException( "ValidateRangeMaxLengthSmallerThanMinLength", null, Metadata.ValidateCountMaxLengthSmallerThanMinLength); } MinLength = minLength; MaxLength = maxLength; } } /// /// Optional base class for implementations that want a default /// implementation to cache valid values. /// public abstract class CachedValidValuesGeneratorBase : IValidateSetValuesGenerator { // Cached valid values. private string[] _validValues; private readonly int _validValuesCacheExpiration; /// /// Initializes a new instance of the class. /// /// /// Sets a time interval in seconds to reset the dynamic valid values cache. /// protected CachedValidValuesGeneratorBase(int cacheExpirationInSeconds) { _validValuesCacheExpiration = cacheExpirationInSeconds; } /// /// Abstract method to generate a valid values. /// public abstract string[] GenerateValidValues(); /// /// Get a valid values. /// public string[] GetValidValues() { // Because we have a background task to clear the cache by '_validValues = null' // we use the local variable to exclude a race condition. var validValuesLocal = _validValues; if (validValuesLocal != null) { return validValuesLocal; } var validValuesNoCache = GenerateValidValues(); if (validValuesNoCache == null) { throw new ValidationMetadataException( "ValidateSetGeneratedValidValuesListIsNull", null, Metadata.ValidateSetGeneratedValidValuesListIsNull); } if (_validValuesCacheExpiration > 0) { _validValues = validValuesNoCache; Task.Delay(_validValuesCacheExpiration * 1000).ContinueWith((task) => _validValues = null); } return validValuesNoCache; } } /// /// Validates that each parameter argument is present in a specified set. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidateSetAttribute : ValidateEnumeratedArgumentsAttribute { // We can use either static '_validValues' or dynamic valid values list generated by instance // of 'validValuesGenerator'. private readonly string[] _validValues; private readonly IValidateSetValuesGenerator validValuesGenerator = null; // The valid values generator cache works across 'ValidateSetAttribute' instances. private static readonly ConcurrentDictionary s_ValidValuesGeneratorCache = new ConcurrentDictionary(); /// /// Gets or sets the custom error message that is displayed to the user. /// The item being validated and a text representation of the validation set is passed as the /// first and second formatting argument to the formatting pattern. /// /// /// [ValidateSet("A","B","C", ErrorMessage="The item '{0}' is not part of the set '{1}'.") /// /// /// public string ErrorMessage { get; set; } /// /// Gets a flag specifying if we should ignore the case when performing string comparison. /// The default is true. /// public bool IgnoreCase { get; set; } = true; /// /// Gets the valid values in the set. /// [SuppressMessage("Design", "CA1065:Do not raise exceptions in unexpected locations", Justification = "")] public IList ValidValues { get { if (validValuesGenerator == null) { return _validValues; } var validValuesLocal = validValuesGenerator.GetValidValues(); if (validValuesLocal == null) { throw new ValidationMetadataException( "ValidateSetGeneratedValidValuesListIsNull", null, Metadata.ValidateSetGeneratedValidValuesListIsNull); } return validValuesLocal; } } /// /// Validates that each parameter argument is present in the specified set. /// /// Object to validate. /// /// if element is not in the set /// for invalid argument /// protected override void ValidateElement(object element) { if (element == null) { throw new ValidationMetadataException( "ArgumentIsEmpty", null, Metadata.ValidateNotNullFailure); } string objString = element.ToString(); foreach (string setString in ValidValues) { if (CultureInfo.InvariantCulture.CompareInfo.Compare( setString, objString, IgnoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) == 0) { return; } } var errorMessageFormat = string.IsNullOrEmpty(ErrorMessage) ? Metadata.ValidateSetFailure : ErrorMessage; throw new ValidationMetadataException( "ValidateSetFailure", null, errorMessageFormat, element.ToString(), SetAsString()); } private string SetAsString() => string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, ValidValues); /// /// Initializes a new instance of the class. /// /// List of valid values. /// For null arguments. /// For invalid arguments. public ValidateSetAttribute(params string[] validValues) { if (validValues == null) { throw PSTraceSource.NewArgumentNullException(nameof(validValues)); } if (validValues.Length == 0) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(validValues), validValues); } _validValues = validValues; } /// /// Initializes a new instance of the class. /// Valid values are returned dynamically from a custom class implementing /// /// /// /// Class that implements the interface. /// /// For null arguments. public ValidateSetAttribute(Type valuesGeneratorType) { // We check 'IsNotPublic' because we don't want allow 'Activator.CreateInstance' create an // instance of non-public type. if (!typeof(IValidateSetValuesGenerator).IsAssignableFrom( valuesGeneratorType) || valuesGeneratorType.IsNotPublic) { throw PSTraceSource.NewArgumentException(nameof(valuesGeneratorType)); } // Add a valid values generator to the cache. // We don't cache valid values; we expect that valid values will be cached in the generator. validValuesGenerator = s_ValidValuesGeneratorCache.GetOrAdd( valuesGeneratorType, static (key) => (IValidateSetValuesGenerator)Activator.CreateInstance(key)); } } /// /// Allows dynamically generate set of values for /// #nullable enable public interface IValidateSetValuesGenerator { /// /// Gets valid values. /// /// A non-null array of non-null strings. string[] GetValidValues(); } #nullable restore /// /// Validates that each parameter argument is Trusted data. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidateTrustedDataAttribute : ValidateArgumentsAttribute { /// /// Validates that the parameter argument is not untrusted. /// /// Object to validate. /// /// The engine APIs for the context under which the validation is being evaluated. /// /// /// if the argument is untrusted. /// protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (ExecutionContext.HasEverUsedConstrainedLanguage && engineIntrinsics.SessionState.Internal.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage) { if (ExecutionContext.IsMarkedAsUntrusted(arguments)) { if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) { throw new ValidationMetadataException( "ValidateTrustedDataFailure", null, Metadata.ValidateTrustedDataFailure, arguments); } SystemPolicy.LogWDACAuditMessage( context: null, title: Metadata.WDACParameterArgNotTrustedLogTitle, message: StringUtil.Format(Metadata.WDACParameterArgNotTrustedMessage, arguments), fqid: "ParameterArgumentNotTrusted", dropIntoDebugger: true); } } } } #region Allow /// /// Allows a NULL as the argument to a mandatory parameter. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class AllowNullAttribute : CmdletMetadataAttribute { /// /// Initializes a new instance of the class. /// public AllowNullAttribute() { } } /// /// Allows an empty string as the argument to a mandatory string parameter. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class AllowEmptyStringAttribute : CmdletMetadataAttribute { /// /// Initializes a new instance of the class. /// public AllowEmptyStringAttribute() { } } /// /// Allows an empty collection as the argument to a mandatory collection parameter. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class AllowEmptyCollectionAttribute : CmdletMetadataAttribute { /// /// Initializes a new instance of the class. /// public AllowEmptyCollectionAttribute() { } } #endregion Allow #region Path validation attributes /// /// Validates that the path has an approved root drive. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ValidateDriveAttribute : ValidateArgumentsAttribute { private readonly string[] _validRootDrives; /// /// Gets the values in the set. /// public IList ValidRootDrives { get => _validRootDrives; } /// /// Initializes a new instance of the class. /// /// List of approved root drives for path. public ValidateDriveAttribute(params string[] validRootDrives) { if (validRootDrives == null) { throw PSTraceSource.NewArgumentException(nameof(validRootDrives)); } _validRootDrives = validRootDrives; } /// /// Validates path argument. /// /// Object to validate. /// Engine intrinsics. protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (arguments == null) { throw new ValidationMetadataException( "PathArgumentIsEmpty", null, Metadata.ValidateNotNullFailure); } if (arguments is not string path) { throw new ValidationMetadataException( "PathArgumentIsNotValid", null, Metadata.ValidateDrivePathArgNotString); } var resolvedPath = engineIntrinsics.SessionState.Internal.Globber.GetProviderPath( path: path, context: new CmdletProviderContext(engineIntrinsics.SessionState.Internal.ExecutionContext), isTrusted: true, provider: out ProviderInfo providerInfo, drive: out PSDriveInfo driveInfo); string rootDrive = driveInfo.Name; if (string.IsNullOrEmpty(rootDrive)) { throw new ValidationMetadataException( "PathArgumentNoRoot", null, Metadata.ValidateDrivePathNoRoot); } bool rootFound = false; foreach (var validDrive in _validRootDrives) { if (rootDrive.Equals(validDrive, StringComparison.OrdinalIgnoreCase)) { rootFound = true; break; } } if (!rootFound) { throw new ValidationMetadataException( "PathRootInvalid", null, Metadata.ValidateDrivePathFailure, rootDrive, ValidDriveListAsString()); } } private string ValidDriveListAsString() { return string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, _validRootDrives); } } /// /// Validates that the path parameter is a User drive. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidateUserDriveAttribute : ValidateDriveAttribute { /// /// Initializes a new instance of the class. /// public ValidateUserDriveAttribute() : base(new string[] { "User" }) { } } #endregion #region NULL validation attributes /// /// Base type of Null Validation attributes. /// public abstract class NullValidationAttributeBase : ValidateArgumentsAttribute { /// /// Check if the argument type is a collection. /// protected bool IsArgumentCollection(Type argumentType, out bool isElementValueType) { isElementValueType = false; var information = new ParameterCollectionTypeInformation(argumentType); switch (information.ParameterCollectionType) { // If 'arguments' is an array, or implement 'IList', or implement 'ICollection<>' // then we continue to check each element of the collection. case ParameterCollectionType.Array: case ParameterCollectionType.IList: case ParameterCollectionType.ICollectionGeneric: Type elementType = information.ElementType; isElementValueType = elementType != null && elementType.IsValueType; return true; default: return false; } } } /// /// Validates that the parameters's argument is not null. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidateNotNullAttribute : NullValidationAttributeBase { /// /// Verifies the argument is not null. If the argument is a collection, verifies that each /// element in the collection is not null. /// /// The arguments to verify. /// /// The engine APIs for the context under which the validation is being evaluated. /// /// /// true if the argument is valid. /// /// /// if element is null or a collection with a null element /// protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (LanguagePrimitives.IsNull(arguments)) { throw new ValidationMetadataException( "ArgumentIsNull", null, Metadata.ValidateNotNullFailure); } else if (IsArgumentCollection(arguments.GetType(), out bool isElementValueType)) { // If the element of the collection is of value type, then no need to check for null // because a value-type value cannot be null. if (isElementValueType) { return; } IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments); while (enumerator.MoveNext()) { object element = enumerator.Current; if (LanguagePrimitives.IsNull(element)) { throw new ValidationMetadataException( "ArgumentIsNull", null, Metadata.ValidateNotNullCollectionFailure); } } } } } /// /// Validates that the parameters's argument is not null, is not an empty string or a /// string with white-space characters only, and is not an empty collection. /// public abstract class ValidateNotNullOrAttributeBase : NullValidationAttributeBase { /// /// Used to check the type of string validation to perform. /// protected readonly bool _checkWhiteSpace; /// /// Validates that the parameters's argument is not null, is not an empty string or a /// string with white-space characters only, and is not an empty collection. /// protected ValidateNotNullOrAttributeBase(bool checkWhiteSpace) { _checkWhiteSpace = checkWhiteSpace; } /// /// Validates that the parameters's argument is not null, is not an empty string, and is /// not an empty collection. If argument is a collection, each argument is verified. /// It can also validate that the parameters's argument is not a string that consists /// only of white-space characters. /// /// The arguments to verify. /// /// The engine APIs for the context under which the validation is being evaluated. /// /// /// if the arguments are not valid. /// protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { if (LanguagePrimitives.IsNull(arguments)) { throw new ValidationMetadataException( "ArgumentIsNull", null, Metadata.ValidateNotNullOrEmptyFailure); } else if (arguments is string str) { if (_checkWhiteSpace) { if (string.IsNullOrWhiteSpace(str)) { throw new ValidationMetadataException( "ArgumentIsEmptyOrWhiteSpace", null, Metadata.ValidateNotNullOrWhiteSpaceFailure); } } else if (string.IsNullOrEmpty(str)) { throw new ValidationMetadataException( "ArgumentIsEmpty", null, Metadata.ValidateNotNullOrEmptyFailure); } } else if (IsArgumentCollection(arguments.GetType(), out bool isElementValueType)) { bool isEmpty = true; IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments); if (enumerator.MoveNext()) { isEmpty = false; } // If the element of the collection is of value type, then no need to check for null // because a value-type value cannot be null. if (!isEmpty && !isElementValueType) { do { object element = enumerator.Current; if (LanguagePrimitives.IsNull(element)) { throw new ValidationMetadataException( "ArgumentIsNull", null, Metadata.ValidateNotNullOrEmptyCollectionFailure); } if (element is string elementAsString) { if (_checkWhiteSpace) { if (string.IsNullOrWhiteSpace(elementAsString)) { throw new ValidationMetadataException( "ArgumentCollectionContainsEmptyOrWhiteSpace", null, Metadata.ValidateNotNullOrWhiteSpaceCollectionFailure); } } else if (string.IsNullOrEmpty(elementAsString)) { throw new ValidationMetadataException( "ArgumentCollectionContainsEmpty", null, Metadata.ValidateNotNullOrEmptyCollectionFailure); } } } while (enumerator.MoveNext()); } if (isEmpty) { throw new ValidationMetadataException( "ArgumentIsEmpty", null, Metadata.ValidateNotNullOrEmptyCollectionFailure); } } else if (arguments is IDictionary dict) { if (dict.Count == 0) { throw new ValidationMetadataException( "ArgumentIsEmpty", null, Metadata.ValidateNotNullOrEmptyCollectionFailure); } } } } /// /// Validates that the parameters's argument is not null, is not an empty string, and is /// not an empty collection. If argument is a collection, each argument is verified. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidateNotNullOrEmptyAttribute : ValidateNotNullOrAttributeBase { /// /// Validates that the parameters's argument is not null, is not an empty string, and is /// not an empty collection. If argument is a collection, each argument is verified. /// public ValidateNotNullOrEmptyAttribute() : base(checkWhiteSpace: false) { } } /// /// Validates that the parameters's argument is not null, is not an empty string, is not a string that /// consists only of white-space characters, and is not an empty collection. If argument is a collection, /// each argument is verified. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class ValidateNotNullOrWhiteSpaceAttribute : ValidateNotNullOrAttributeBase { /// /// Validates that the parameters's argument is not null, is not an empty string, is not a string that /// consists only of white-space characters, and is not an empty collection. If argument is a collection, /// each argument is verified. /// public ValidateNotNullOrWhiteSpaceAttribute() : base(checkWhiteSpace: true) { } } #endregion NULL validation attributes #endregion Data validate Attributes #region Data Generation Attributes /// /// Serves as the base class for attributes that perform argument transformation. /// /// /// Argument transformation attributes can be attached to and /// parameters to automatically transform the argument /// value in some fashion. The transformation might change the object, convert the type, or /// even load a file or AD object based on the name. Existing argument transformation attributes /// include . /// Custom argument transformation attributes should derive from /// and override the /// abstract method, after which they /// can apply the attribute to their parameters. /// It is also recommended to override to return a readable /// string similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]". /// If multiple transformations are defined on a parameter, they will be invoked in series, /// each getting the output of the previous transformation. /// /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public abstract class ArgumentTransformationAttribute : CmdletMetadataAttribute { /// /// Initializes a new instance of the class. /// protected ArgumentTransformationAttribute() { } /// /// Method that will be overridden by the subclasses to transform the /// parameter argument into some other object that will be used for the parameter's value. /// /// /// The engine APIs for the context under which the transformation is being made. /// /// Parameter argument to mutate. /// The transformed value(s) of . /// Should be thrown for invalid arguments. /// /// Should be thrown for any problems during transformation. /// public abstract object Transform(EngineIntrinsics engineIntrinsics, object inputData); /// /// Transform and track the flow of untrusted object. /// NOTE: All internal handling of should use this method to /// track the trustworthiness of the data input source by default. /// /// /// The default value for is true. /// You should stick to the default value for this parameter in most cases so that data input source is /// tracked during the transformation. The only acceptable exception is when this method is used in /// Compiler or Binder where you can generate extra code to track input source when it's necessary. /// This is to minimize the overhead when tracking is not needed. /// internal object TransformInternal( EngineIntrinsics engineIntrinsics, object inputData, bool trackDataInputSource = true) { object result = Transform(engineIntrinsics, inputData); if (trackDataInputSource && engineIntrinsics != null) { ExecutionContext.PropagateInputSource( inputData, result, engineIntrinsics.SessionState.Internal.LanguageMode); } return result; } /// /// The property is only checked when: /// a) The parameter is not mandatory /// b) The argument is null. /// public virtual bool TransformNullOptionalParameters { get => true; } } #endregion Data Generation Attributes }