Did you know? #3

PowerShell Team

Did you know that you can put constraints on variables using the same
attributes as cmdlet parameters?
Unfortunately we had to postpone the language support for this but you can
still do it using new-object.

MSH > $a = “foo”
MSH > $varA = get-variable a
MSH > $varA

Name                           Value
—-                           —–
a                              foo

MSH > $varA.Attributes.Add($(new-object
System.Management.Automation.ValidateLengthAttribute -arg 1,10))
MSH > $a = “”
 : Cannot validate because of invalid value () for variable a.
At line:1 char:3
+ $a  <<<< = “”
MSH > $a = “somethingreallylong”
 : Cannot validate because of invalid value (somethingreallylong) for
variable
a.
At line:1 char:3
+ $a  <<<< = “somethingreallylong”
MSH > $a = “just right”
MSH > $a
just right

-Jeff Jones

[Edit: Monad has now been renamed to Windows PowerShell. This script or discussion may require slight adjustments before it applies directly to newer builds.]

0 comments

Discussion is closed.

Feedback usabilla icon