0

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?

Richard
  • 63
  • 1
  • 9
  • [1] you cannot chain logical operators like that. >>> `($collect -ne ('basic' -or 'medium' -or 'full'))` <<< the structure is simply not valid. try it out on its own. [*grin*] ///// [2] PoSh has validation methods - take a look at the following ... Simplify Your PowerShell Script with Parameter Validation | Scripting Blog — https://devblogs.microsoft.com/scripting/simplify-your-powershell-script-with-parameter-validation/ – Lee_Dailey May 25 '21 at 16:43
  • Why not just use the `ValidateSet` attribute? `[ValidateSet('basic','medium','full')]` – Abraham Zinala May 25 '21 at 16:44
  • "I know that i could use validateset, but this dont work for me. " <- why not? – Mathias R. Jessen May 25 '21 at 16:45

1 Answers1

0

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
)
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • The problem with Validateset is that if i stablish a -help parameter (example: [switch]$help; if ($help){write-host "help output"}) -help does not work alone without -collect too – Richard May 25 '21 at 16:58
  • 2
    @Richard The solution to that is to NOT attempt to reinvent the wheel by defining your own custom `-help` parameter :-) – Mathias R. Jessen May 25 '21 at 17:04
  • I'm just starting to learn powershell. So do you mean there's a default "-help" parameter that i can use? Any example or reference? – Richard May 25 '21 at 17:10
  • 2
    @Richard Yes. It's `-?`, not `-help`. Like, `.\path\to\yourScript.ps1 -?` – Mathias R. Jessen May 25 '21 at 17:10