Using Script Validators with Variables

by Aug 5, 2013

As pointed out in a previous tip, PowerShell 3.0 now supports the use of validators for variable assignments. This is a great way of ensuring that a variable cannot contain illegal data. One of the most versatile validators is the ValidateScript attribute.

This example makes sure the variable $future contains a date that is in the future. Whenever a script tries and assigns a date to this variable that is in the past, an error is raised, drawing attention to the problem:

[DateTime][ValidateScript({$_ -ge (Get-Date)})]$future = '2014-12-10' 

Try for yourself, and after you run this code, assign a date of the past to $future:

ValidateScript simply expects a script block. Inside of it, $_ represents the value that is going to be assigned to the variable. If the script block returns $false, the value is not assigned and instead an error is raised.

You can do much more complex things using this approach. This example only accepts file names that exist in the System32 folder:

[String][ValidateScript({ Test-Path $env:windir\system32\$_ })]$DLLFile = 'avrt.dll'

And here are the results: assigning a file name that does not exist will again raise an error:

Twitter This Tip! ReTweet this Tip!