Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

PowerShell Scripting with [ValidateRange]

Posted on April 11, 2012May 15, 2012

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.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!


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.


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

9 thoughts on “PowerShell Scripting with [ValidateRange]”

  1. Ted the Chilehead says:
    April 11, 2012 at 1:30 pm

    Very helpful for something I’m trying to do for automated cleanup scripts using Windows Scheduler. Thanks for the post!

    1. Jeffery Hicks says:
      April 11, 2012 at 1:45 pm

      It is always fun to find a timely tip. Glad it helped.

  2. walid toumi says:
    April 11, 2012 at 11:01 pm

    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. Jeffery Hicks says:
      April 12, 2012 at 8:13 am

      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. Jeffery Hicks says:
        April 12, 2012 at 8:22 am

        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.

  3. walid toumi says:
    April 11, 2012 at 11:41 pm

    also:

    function foo-int32 {
    Param (
    [Parameter()]
    [ValidateRange(5*7,8*6)]
    $inter
    )
    $inter
    }

  4. Pingback: PowerShell Scripting with [ValidateScript] | The Lonely Administrator
  5. Pingback: PowerShell Scripting with [ValidateSet] | The Lonely Administrator
  6. Pingback: Parameter validation « Mario's Blog

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d