Search code examples
powershellparameters

Validating Default value


I am trying to validate null or empty values for the variables $var1 and $var2. Can someone tell what I am doing wrong?

testing.ps1:

Param (
    [ValidateNotNullOrEmpty()][String]$var1 = $defaultvar1,
    [ValidateNotNullOrEmpty()][String]$var2 = $defaultvar2
)
Write-Host "Value of Variable 1 : $var1 "
Write-Host "Value of Variable 2 : $var2 "

Output:

PS> .\testing.ps1
Value of Variable 1 :
Value of Variable 2 :
PS> $defaultvar1=123
PS> $defaultvar2=678
PS> .\testing.ps1
Value of Variable 1 : 123
Value of Variable 2 : 678
PS> $defaultvar2=""
PS> .\testing.ps1
Value of Variable 1 : 123
Value of Variable 2 :

Solution

  • As Lee_Dailey points out:

    Parameter default values are not validated - the assumption is that you, as the function author, will ensure that the values are valid.

    A simpler example:

    PS> & { param([ValidateNotNullOrEmpty()] $foo = '') "foo: [$foo]" }
    foo: []
    

    That is, '' was happily accepted as the default value, even though it contradicts [ValidateNotNullOrEmpty()].

    Additionally, you generally shouldn't use function-external variable values as parameter default values, because it'll make the function's behavior hard to predict.

    Instead, use:

    • literals (e.g., $foo = 'bar')

    or

    • expressions (e.g., $foo = (Get-Date))

    That said, as Mike Shepard points out, referencing variables is an option, if:

    • your function is defined inside a module,
    • and the variables being referenced are defined in that same module.