Home > Software design >  Powershell integer parameter validation with multiple ranges
Powershell integer parameter validation with multiple ranges

Time:09-09

I know you can declare an integer parameter that only accepts values within a specific range:

[Parameter()][ValidateRange(1024,66535)]$Port

Is it possible to validate parameter input for several ranges? For example, say I want to allow port inputs to be 1 through 80, 135 through 445, and 1024 through 65535, I could do it with:

[Parameter()][ValidateRange(1,66535)]$Port

if ((($Port -gt 80) -and ($Port -lt 135)) -or (($Port -gt 445) -and ($Port -lt 1024))) {
    
    Write-Error "Incorrect input, please enter a value between 1-80, 135-445, or 1024-65535"
    break

}

However that doesn't strike me as a particularly neat way of doing things. ValidateSet() also can't take number ranges like 1024..65535. Anyone have a better idea of input validation for multiple integer ranges?

CodePudding user response:

You can definitely implement your custom ValidateRange attribute declaration by creating a class that inherits from the ValidateEnumeratedArgumentsAttribute Class. Here is a little example:

class ValidateCustomRange : Management.Automation.ValidateEnumeratedArgumentsAttribute {
    [void] ValidateElement([object] $Element) {
        if($Element -gt 80 -and $Element -lt 135 -or $Element -gt 445 -and $Element -lt 1024) {
            $errorRecord = [Management.Automation.ErrorRecord]::new(
                [Exception] 'Invalid range! Must be ...your call here :)',
                'InvalidRange',
                [Management.Automation.ErrorCategory]::InvalidOperation,
                $Element
            )
            throw $errorRecord
        }
    }
}

function Test-Range {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateCustomRange()]
        [int] $Port
    )
}

Test-Range 80 # All good!
Test-Range 81 # Error
  • Related