Home > Back-end >  Check for use of comma in multiple strings passed as parameters in Powershell
Check for use of comma in multiple strings passed as parameters in Powershell

Time:08-03

I have a script that takes two parameters: one takes a single string, the other takes two strings. For the script to function correctly both strings have to be separated by a comma. When using the script if the user does not use the comma, Powershell throws and error which does not say anything about using the comma. How can I customize that error message. I've tried with ValidateScript but i can`t make it to work. This is what I have:

Param (
      [Parameter(Mandatory=$false, ParameterSetName="OptionA")]
      [String] $OptionA,

      [Parameter(Mandatory=$false, ParameterSetName="OptionB")]
      [ValidateCount(2,2)]
      [ValidateScript({
          if ($_.ToString().Contains(",")) {
            $true
          } else {
              Throw "$_ use comma to separate the two strings!"  
          }
      })]
      [String[]] $OptionB
)

if ($OptionA) {
      Write-Host $OptionA
      return
}

if ($OptionB) {
      Write-Host $OptionB
      return
}

Write-Host "Not a valid parameter!"

CodePudding user response:

Another possible setup using only a single Option parameter.

Note: Wrapped in function for testing purposes.

Function Test {
    [CmdletBinding()]
    Param (
      [Parameter(Mandatory=$True)]
        [string[]] $Option
    )

    Switch ($option.Count) {
      1  {"Single Parameter"}
      2  {"Two Parameters"}
      Default {"More than two Parameters"}
    } #End Switch

} #End Function
 
Clear-Host
  
Test "Parameter 1","Parameter 2"

You can choose to let run as it stands since it will prompt for missing parameter or you can change to Mandatory=$False and add validation for Null.

CodePudding user response:

PowerShell itself parses ,-separated tokens that make up an array-valued command argument into an array, so that your [String[]]-typed $OptionB parameter already sees the ,-separated tokens as individual array elements.

However, the script block passed to the [ValidateScript()] attribute is invoked for each element of the array being passed, so you cannot validate the array as a whole there.

Therefore, your only option is to perform the validation in your script's body, after all parameters have been bound:

param (
      [Parameter(Mandatory=$false, ParameterSetName="OptionA")]
      [String] $OptionA,

      [Parameter(Mandatory=$false, ParameterSetName="OptionB")]
      [String[]] $OptionB
)

if ($PSCmdlet.ParameterSetName -eq 'OptionB' -and $OptionB.Count -ne 2) {
  Throw "Exactly two comma-separated strings must be passed."  
}

  • Related