Profile cover photo
Profile photo
Edi Prinz
84 followers
84 followers
About
Posts


I just stumbled across a bug in most (if not all) powershell documentations!
As you all know, powershell has built in parameter validation - have a look at this:

function test{
    Param (
        [ValidateRange(3,8)]
        [Int] $mytest )

    write-host $mytest
}
test(4)
test(9)

Obviously this results in:

4
test : Cannot validate argument on parameter 'mytest'. The 9 argument is greater than the maximum allowed range of 8. Supply an argument that is less than or equal to 8 and then try the command again.

But now change this little piece of code to this:

function test{
    Param    (
        [ValidateRange(3,8)]
        [Int] $mytest)

    $mytest = $mytest+5
    write-host $mytest
}

test(4)

You would expect the function to write "9", but as parameter validation is in fact not parameter validation, but variable validation the result in fact is:
The variable cannot be validated because the value 9 is not a valid value for the mytest variable.

So this is not only a one-time parameter validation but a validation of the value of the variable during the whole lifetime of the variable. Due to this also something like this is possible:
function test{

    [validaterange(1,3)][int] $mytest=2
    write-host $mytest
    $mytest = 5
    write-host $mytest
}
test

Here we don't have any parameters, but the variable is still validated:
2
The variable cannot be validated because the value 5 is not a valid value for the mytest variable.
 
2

As you can see, if the validation fails the variable still has the value of the last successfull assignment of a value - in this case "2"
This means parameter validation is nothing by variable validation during the call to the function and doesn't have any impact on the fact, that the variables are still validated.

Hi everyone,

I waited for the arrival of a powershell class ability since the first versions. Guess what - I was so excited to have Powershell 5 installed on my system o few weeks ago. Class themselves work just fine, but is it really true, that there is no class inheritance, or did I miss something?
Wait while more posts are being loaded