Powershell Need to pass multiple values to variables in Powershell via Read-Host

Before we get going, YES, we MUST use Read-Host.

I’m creating a script to "do something"

but first the end user has to input the values necessary (dept#). If it were always a set number of values, this would be easy. But it’s not always a set number of values

$response = Read-Host 'Enter the department you want to index (e.g., dept00) or press N'
if ($response -ne 'n') {
<do things based on user input>
}
until ($response -eq 'N')

The catch is that it might be dept00, dept05, dept16 today but tomorrow it might be 20 different departments. This must be entered manually by the end user.

Each can take about 5 min to run, so I’d prefer if all of the ‘depts’ could be entered first then it all runs after the user enters the dept numbers.

Any thoughts or suggestions appreciated.

>Solution :

There isn’t really, as you have stated in comments, a bulletproof way to handle this but you can get closer to something robust using a regex pattern to check if the inputted value starts with the word dept followed by 2 numeric digits ([0-9]{2}). You can repeat this process using a while loop and, in addition to the previous check, you can use a HashSet<T> to skip duplicated values inputted by the user. The end result of this function would be an array of "valid departments":

function Read-Department {
    $departments = [System.Collections.Generic.HashSet[string]]::new(
        [System.StringComparer]::InvariantCultureIgnoreCase)

    while ($true) {
        $response = (Read-Host 'Enter the department you want to index (e.g., dept00) or press N').Trim()
        if ($response -eq 'N') {
            return $departments
        }

        if ($response -notmatch '^dept[0-9]{2}$') {
            Write-Warning "Inputted value '$response' does not meet criteria."
            continue
        }

        if (-not $departments.Add($response)) {
            Write-Warning "Inputted value '$response' is duplicated, skipping."
        }
    }
}

$departmentsToProcess = Read-Department
$departmentsToProcess

Leave a Reply