en-us/about_Scripting_ValidateRange.help.txt

TOPIC
    about_Scripting_ValidateRange
 
SHORT DESCRIPTION
    A tutorial on verifying if a parameter value falls in a given range.
     
LONG DESCRIPTION
    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
    )
 
    $m="Getting top {0} processes from {1} sorted by {2}" -f $Count,$Computername,$Property
     
    Write-Host $m -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 C:\Scripts> .\Demo-ValidateRange.ps1 -Count 25
    C:\scripts\Demo-ValidateRange.ps1 : Cannot validate argument on parameter
    'Count'. 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],
        ParameterBindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,Demo-Valid
        ateRange.ps1
 
    PS C:\Scripts> .\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.
     
 
SEE ALSO
    about_Functions_Advanced_Parameters
    http://jdhitsolutions.com/blog