arraysstringpowershellparametersread-host

[string[]] Parameter vs Read-Host behaviour


Within my PowerShell script I have parameter set for :

[string[]]$OptionNum

So I can call my script using for instance :

.\MyScript.ps1 1,4,6

I then have a switch statement on $OptionNum for PSItem –contains “n” with each option value, to run the relevant code depending on what has been selected. So above, the individual switch options for 1, 4 and 6 are each called. That works fine.

The problem. If the user hasn’t specified those options at the prompt, I’d like to show them the list of available options, and allow them to enter the items they want. So I’ve outputted the info on what is available, and then I have a line :

[string[]]$OptionNum = Read-Host “Enter the required options”

While in both cases $OptionNum is set as a string System.Array type, using the parameter method above the array has three distinct values, but the Read-Host method using the same values entered the same way gives me a single array value of “1,4,6”. Or put another way, $OptionNum.count is 3 when using the parameter, and 1 when using Read-Host.

How do I adjust my Read-Host code so those comma separated values are saved as separate entries in the array?

Note, the $OptionNum values are string values not numbers and could be a word rather than a number. I want the user experience to be same whichever method they use to enter the options, so the code can change, but what's entered by the user can't.


Solution

  • I guess you just do it this way:

    $OptionNum = (Read-Host “Enter the required options”) -split ','|%{if($_){$_.trim()}}

    The result string of Read-Host gets splitted in the commas and the you loop over that array asking if there is a value (if for some reason your user leaves a comma at the end or their input begins with a comma) you trim the trailing whitespaces at the beginning and end (because if user input is '1, 2, 3, 4,6 , 7' or something among those things users like to do)