PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

Geek Sync Live

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.

Latest Scripts

10-07-2015 - Clone NTFS ACL Version 1.0.0
09-19-2015 - Bryan's Games Galore!
09-18-2015 - Bryan's Process Help

As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Adding ValidateRange to a Variable

If you'd like to apply a numeric range of legal values to a variable, you can add a ValidateRange attribute to the variable, pretty much like function parameters work. Except, with variables you need to do it manually:

$test = 1
$variable = Get-Variable test
$validateRange = New-Object -TypeName System.Management.Automation.ValidateRangeAttribute(1,100)

$test = 10
$test = 100
$test = 1000 

The variable $test now accepts numeric values in the range from 1 to 100. When you try and assign a value outside the range, you get an exception.

PS C:\> $test =  101
The variable cannot be  validated because the value 101 is not a valid value for the test 
At line:1 char:1
+ $test = 101
+ ~~~~~~~~~~~
    +  CategoryInfo          : MetadataError:  (:) [], ValidationMetadataException
    +  FullyQualifiedErrorId : ValidateSetFailure 

Twitter This Tip! ReTweet this Tip!

Copyright 2012 PowerShell.com. All rights reserved.