我有一个脚本在等待用户输入,然后根据他们按的内容执行操作。但是,问题是无论脚本按什么键,脚本都会继续运行(但是,如果它不是期望的两个键之一,那么我只会得到错误)。这是我正在努力的摘要
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
我想要的是,如果按了
c
或u
之外的任何命令,则告诉用户这不是有效的键,然后返回此摘要的顶部,并再次提示用户下一步要执行的操作。 最佳答案
只要将您的代码包装在do-while
循环中,只要$value
不是c
或u
,该循环就会继续:
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')
关于powershell - 在按下某些键之前,Powershell不会继续,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38139186/