2
votes

Is it possible to make a Paramater validateset work with a wildcard?

I would want on the * places to accept 0-100.

param
  (
    [Parameter(Mandatory=$True)]
    [validateset("6.1.*.*")]
    [string]$variable
  )

Error message:

Cannot validate argument on parameter 'variable'. The argument "6.1.1.0" does not belong to the set "6.1.." specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. + CategoryInfo : InvalidData: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ParameterArgumentValidationError

2

2 Answers

4
votes

Since it looks like you're looking to validate a version, you may want to declare the parameter of the type [version] and use the ValidateScript attribute to validate the value rather than using string matching:

function Test-Version {
  param(
    [ValidateScript({
        $_.Major -eq '6' -and 
        $_.Minor -eq '1' -and
        $_.Build -in (0..100) -and
        $_.Revision -in (0..100) -or 
        $(throw 'Wrong Version')
      })]
    [version]$Version
  )    
}
4
votes

No, that's what [ValidatePattern()] is for:

param(
    [Parameter(Mandatory=$True)]
    [ValidatePattern('6\.1\.\d{1,3}\.\d{1,3}')]
    [string]$variable
)

It takes a regular expression as the parameter.

[ValidateSet()] is meant to be used if there is a small, constant set of values. PowerShell also provides autocompletion for these. For example:

[ValidateSet('Windows', 'Mac', 'Linux')
$OperatingSystem

See this article for more parameter validation attributes.