Powershell不会继续,直到某些按键被按下

时间:2016-07-01 07:10:34

标签: powershell

我有一个脚本等待用户输入,然后取决于他们按什么做什么。但问题是,无论他们按什么脚本,脚本都会继续(但如果它不是它预期的两个键中的一个,我只会得到错误)。这是我正在研究的狙击手

Write-Host "What do you want to do next?" -nonewline
Write-Host "

    u - Search for another user
    c - Enter a computer name

"

# Prompt for an action
Write-Host ">> Select shortcut action: " -nonewline

$key = [Console]::ReadKey()
$value = $key.KeyChar

switch($value) {
    c { $c = Read-Host "Enter computer or IP"}
    u { $u = Read-Host "Enter user" }
}


# now we continue on with the code depending on what was pressed

我喜欢的是,如果按下cu之外的任何内容,则告诉用户该用户不是有效密钥并返回到此snippint的顶部并提示用户再次采取下一步行动。

1 个答案:

答案 0 :(得分:2)

只需将代码包装在do-while循环中,只要$value不是cu,就会继续执行此代码:

do 
{
    $key = [Console]::ReadKey($true)
    $value = $key.KeyChar

    switch($value) {
        c { $c = Read-Host "Enter computer or IP"}
        u { $u = Read-Host "Enter user" }
    }
}
while ($value -notmatch 'c|u')