Search code examples
powershellvalidateset

Parameter validation


Im trying to validate a parameter called "Collect" to accept only 3 parameters (basic, medium and full) but when i asign a "valid" value to the "collect" parameter, it got a "false" return.

Thats what i did:

[CmdLetBinding()]
param([string]$Collect)
)

if ($collect -ne ('basic' -or 'medium' -or 'full')) {
  Write-Host "'collect' is mandatory with mandatory values. For reference, use -help argument" -ForegroundColor Red
  exit
}

Running test:

c:\script.ps1 -collect basic

'collect' is mandatory with mandatory values. For reference, use -help argument

PD: -I know that i could use validateset, but this dont work for me. -I think the problem is in the nested $collect -ne ('basic' -or 'medium' -or 'full'), but how can i solve it?


Solution

  • An -or operation always evaluates to a [bool] - so your if condition is basically $collect -ne $true.

    You'll want to use -notin instead of -ne:

    if($collect -notin 'basic','medium','full'){ 
       # ...
    }
    

    Or better yet, just use a ValidateSet attribute:

    param(
      [ValidateSet('basic','medium','full')]
      [string]$Collect
    )