ValidateArgumentsAttribute

Validators that inherit from ValidateArgumentsAttribute are somewhat difficult to define. The existing validators, such as ValidateNotNullOrEmpty and ValidateCount, catch most of the possible uses. Validation is more often interested in testing whether the value of parameter is an array.

Classes that inherit from ValidateArgumentsAttribute act on an argument as a single entity. If an argument is an array, the validation step applies to the array object rather than the individual elements of the array.

Classes that implement ValidateArgumentsAttribute must inherit from System.Management.Automation.ValidateArgumentsAttribute. The class must implement a Validate method that is marked as abstract in the ValidateArgumentsAttribute class.

The Validate method accepts two arguments with the System.Object and System.Management.Automation.EngineIntrinsics types. This is shown in the .NET reference: https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.validateargumentsattribute.validate?view=powershellsdk-1.1.0.

The following example tests that the argument is not null or whitespace:

using namespace System.Management.Automation

class ValidateNotNullOrWhitespaceAttribute : ValidateArgumentsAttribute {
[Void] Validate(
[System.Object]$arguments,
[EngineIntrinsics]$engineIntrinsics
) {
if ([String]::IsNullOrWhitespace($arguments)) {
throw 'The value cannot be null or white space'
}
}
}

The use of this validator is demonstrated in the following function:

function Test-Validate {
[CmdletBinding()]
param (
[ValidateNotNullOrWhitespace()]
[String]$Value
)

Write-Host $Value
}

This validator example will be more effective when defined as a validator that inherits from ValidateEnumeratedArguments and is implemented in the ValidateElement method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.8.82