提问人:ubercaw 提问时间:9/27/2023 最后编辑:Ken Whiteubercaw 更新时间:9/27/2023 访问量:36
如何通过在两个提示中的任何一个中键入“quit”来取消 while 循环
How to cancel a while loop by typing 'quit' into either of two prompts
问:
我为我们的区域办事处制作了打印机安装脚本。它首先询问您在哪个办公室,并询问您是否要添加或删除打印机
我正在尝试使用户能够在这些提示中键入“quit”并退出 while 循环。目前,仅当您在第二个提示中键入“quit”时,它才有效。
我试过了
while ($install -ne 'quit' -AND $office -ne 'quit'){}
和
while ($install -ne 'quit' -OR $office -ne 'quit'){}
原来是
while ($install -ne 'quit'){}
当您在第二个提示符中键入它时,所有提示符都有效,该提示符是 的读主机。如果我打印出的值,我可以看到它存储“退出”,但我显然在逻辑中遗漏了一些东西,以便在存储该值时让它停止。$install
$office
这是整个脚本(至少足够了解它是如何工作的)。
cls
$install = ''
$office = ''
while ($install -ne 'quit' -and $office -ne 'quit'){
$office = read-host Which office are you in? "(GOL, SUN, CNS, TSV)"
$install = read-host Type "add" to install, "remove" to uninstall or "quit" to quit the program
If ($office -eq 'gol' -or $install -eq 'add'){
add-printerport 20.45.50.32 -PrinterHostAddress 20.45.50.32
"Adding printer port 20.45.50.32"
""
add-printer -name "GOL Direct Print" -DriverName "FX ApeosPort-VII C7788 PS" -PortName 20.45.50.32
"Adding printer GOL Direct Print AKA FX ApeosPort-VII C7788 PS at IP address 20.45.50.32"
""
"Script complete, you can test printing now to 'GOL Direct Print'."
}
elseif ($office -eq 'gol' -and $install -eq 'remove'){
remove-printer -name "GOL Direct Print"
""
"Removing printer GOL Direct Print"
""
remove-printerport 20.45.50.32
"Removing printer port 20.45.50.32
""
"Old printer has been removed, run the script again to install"
}
该脚本还有几个与上述格式相同的语句,但仅此而已。elseif
答:
0赞
Santiago Squarzon
9/27/2023
#1
这是您尝试实现的目标的简化版本,您可以使用 break
关键字退出循环,并且您可以使用而不是 2 个条件来简化条件。while
-contains
if
建议使用 ,因为会寻找完全匹配,任何多余的空格都会使条件失败。.Trim()
-contains
while ($true) {
$office = Read-Host "Which office are you in? '(GOL, SUN, CNS, TSV)'"
$install = Read-Host "Type 'add' to install, 'remove' to uninstall or 'quit' to quit the program"
if ($office.Trim(), $install.Trim() -contains 'quit') {
break
}
# do other stuff here
'hi!'
}
上一个:组合逻辑向量以创建非逻辑向量
评论
if ($install -eq 'quit') { break }
?