Powershell: decorator validator with variable

Created on 27 Jan 2020  路  3Comments  路  Source: PowerShell/PowerShell

steps to reproduce

$a = 8
$b = 14

[ValidateRange($a,$b)]$number = Read-Host "Enter number Between 8 and 14"

this return error. i known we can use instead validatescript but this decorator its not specific to range or length...etc otherwise why create such decorators if validatescript can do everything

Issue-Enhancement Resolution-Answered

Most helpful comment

Attributes require static values in order to be able to compile. As far as I know this would create uncompilable code.

In order to allow this, PS would have to retrieve variable values at the time the variable or function is defined, effectively defeating the purpose of doing so.

I'd also generally be quite worried about any code written this way. Having functions that effectively have a fluid definition based on runtime state creates difficult to trace errors and unpredictable functions. The point of defining a function is to have a replicable block of code that always behaves the way it was originally defined.

All 3 comments

Attributes require static values in order to be able to compile. As far as I know this would create uncompilable code.

In order to allow this, PS would have to retrieve variable values at the time the variable or function is defined, effectively defeating the purpose of doing so.

I'd also generally be quite worried about any code written this way. Having functions that effectively have a fluid definition based on runtime state creates difficult to trace errors and unpredictable functions. The point of defining a function is to have a replicable block of code that always behaves the way it was originally defined.

You could try to add an attribute dynamically in run time.

This issue has been marked as answered and has not had any activity for 1 day. It has been closed for housekeeping purposes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Michal-Ziemba picture Michal-Ziemba  路  3Comments

alx9r picture alx9r  路  3Comments

JohnLBevan picture JohnLBevan  路  3Comments

aragula12 picture aragula12  路  3Comments

ajensenwaud picture ajensenwaud  路  3Comments