Tony Mathew Thomas
Tony Mathew Thomas

Reputation: 95

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 :

Upvotes: 3

Views: 466

Answers (2)

mklement0
mklement0

Reputation: 437109

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.

Upvotes: 2

vandre
vandre

Reputation: 828

I ran into this same issue. My solution was to validate twice:

Param (
    [ValidateNotNullOrEmpty()][String]$var1 = $script:defaultVar1,
    [ValidateNotNullOrEmpty()][String]$var2 = $script:defaultVar2
)
if([string]::IsNullOrEmpty($var1)){ throw "var1 was not provided and defaultVar1 is null or empty" }
if([string]::IsNullOrEmpty($var2)){ throw "var2 was not provided and defaultVar2 is null or empty" }

Write-Host "Value of Variable 1 : $var1 "
Write-Host "Value of Variable 2 : $var2 "

The ValidateNotNullOrEmpty attribute takes care of validating inbound parameters, while IsNullOrEmpty handles the edge case where defaultVar1 or defaultVar2 are empty

I find this pattern useful when writing a module where the user can configure default values for commonly used options.

Upvotes: 0

Related Questions