PowerShell Scripting with [ValidateRange]

After my post yesterday on using the ValidateScript attribute with PSCredentials, I thought you might find it helpful to have a brief discussion on some other parameter validation attributes such as [ValidateRange()]. You can use this attribute if you want to verify that a given parameter value falls between some range. Typically this is used for numeric values. This attribute is quite easy to use. Here’s a sample script.


Param (
[Parameter(Position=0)]
[string]$Property="WorkingSet",
[Parameter(Position=1,Mandatory=$True,HelpMessage="How many top processes do you want? The maximum is 20.")]
[ValidateRange(1,20)]
[string]$Count,
[ValidateNotNullOrEmpty()]
[string]$Computername=$env:computername
)

$msg="Getting top {0} processes from {1} sorted by {2}" -f $Count,$Computername,$Property
Write-Host $msg -ForegroundColor Green

Get-Process -ComputerName $computername | Sort -Property $property -Descending | Select -first $Count

This script gets the top X number of processes from a computer based on a user-specified property. The default property is WorkingSet. The Count property has [ValidateRange()] attribute that dictates that any value must be between 1 and 20. If you enter a value outside of that range, PowerShell will throw an exception and the script will not run.


PS S:\> .\Demo-ValidateRange.ps1 -Count 25
C:\scripts\Demo-ValidateRange.ps1 : Cannot validate argument on parameter 'Coun
t'. The 25 argument is greater than the maximum allowed range of 20. Supply an
argument that is less than 20 and then try the command again.
At line:1 char:32
+ .\Demo-ValidateRange.ps1 -Count <<<< 25
+ CategoryInfo : InvalidData: (:) [Demo-ValidateRange.ps1], Param
eterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Demo-ValidateRa
nge.ps1

PS S:\>.\Demo-ValidateRange.ps1 -Count 3
Getting top 3 processes from SERENITY sorted by WorkingSet

Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
2288 121 201804 287396 622 1,748.24 7088 chrome
775 111 254700 263620 501 102.31 8104 thunderbird
619 39 254124 261376 472 2,155.51 1152 svchost

Of course, you can skip this and add your own validation test within your script if you prefer to handle errors on your own and perhaps a bit more gracefully.

Using [ValidateRange()] really only works with numeric values. If you wanted to validate if a datetime value fell within a range, you’ll have to turn to something else. At least I have yet to find a way to use [ValidateRange()] with anything other than numbers. But we have options and I’ll be back to show you some of them.

9 thoughts on “PowerShell Scripting with [ValidateRange]”

  1. hi,

    here some test

    with numeric

    function foo-int32 {
    Param (
    [Parameter()]
    [ValidateRange(500kb,200mb)]
    $inter
    )
    $inter
    }

    with date:

    function foo-date {
    Param (
    [Parameter()]
    [ValidateRange('1/1/2012','1/3/2012')]
    $date
    )
    $date
    }

    with letter:

    function foo-letter {
    Param (
    [Parameter()]
    [ValidateRange('e','f')]
    $letter
    )
    $letter
    }

    with time:

    function foo-time {
    Param (
    [Parameter()]
    [ValidateRange("03:36:40", "03:36:49")]
    $time
    )
    $time
    }

    1. Interesting. I know that anything that is numeric will work so 1MB,10MB is no problem. The Date works but only if you do NOT cast the parameter variable to a [datetime]. The ValidateRange attribute seems to be doing that automatically. So this would be an exception to the best practice.

      1. Hold on a second. The date example (and I’m presuming the time one) don’t really work based on my testing. More to come.

Comments are closed.