Powershell需要通过Read-Host将多个值传递给Powershell中的变量

htrmnn0y  于 5个月前  发布在  Shell
关注(0)|答案(1)|浏览(101)

在我们开始之前,是的,我们必须使用Read-Host。
我在写一个脚本来“做点什么”
但首先,终端用户必须输入必要的值(部门编号)。如果它总是一组值,这将很容易。但它并不总是一组值

$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')

字符串
问题是,今天可能是dept 00,dept 05,dept 16,但明天可能是20个不同的部门。这必须由最终用户手动输入。
每个可以采取约5分钟的运行,所以我宁愿如果所有的'部门'可以输入第一,然后它都运行后,用户输入的部门号码。
任何想法或建议赞赏。

kwvwclae

kwvwclae1#

正如你在评论中所说的,并没有一个真正的“防弹”方法来处理这个问题,但是你可以使用正则表达式模式来检查输入的值是否以单词dept开头,后跟2个数字([0-9]{2}。此外,您可以使用HashSet<T>来获取唯一值。然后可以使用while loop重复此过程,直到用户输入等于N

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

字符串

相关问题