PowerShell打印机脚本:实现输入quit从任意提示退出while循环
问题解决:PowerShell脚本中输入'quit'无法在第一个提示时退出循环
问题根源
你的循环逻辑是先判断条件,再执行输入操作。当你在第一个Read-Host(输入$office)时输入'quit',脚本不会立即检查退出条件,而是会继续执行第二个Read-Host(输入$install),直到当前循环迭代结束,下一次循环开始时才会判断条件——这就是为什么只有在第二个输入框打'quit'才会立即退出的原因。
修复方案
核心思路是:在每次获取用户输入后,立即检查是否为'quit',如果是就直接跳出循环。可以把循环改成while($true)的无限循环,然后在关键节点添加退出判断。
修改后的核心代码示例:
cls $install = '' $office = '' while ($true) { $office = Read-Host "Which office are you in? (GOL, SUN, CNS, TSV)" # 第一个输入为quit时直接退出循环 if ($office -eq 'quit') { break } $install = Read-Host "Type `"add`" to install, `"remove`" to uninstall or `"quit`" to quit the program" # 第二个输入为quit时直接退出循环 if ($install -eq 'quit') { break } # 原有的打印机操作逻辑 if ($office -eq 'gol' -and $install -eq 'add') { Add-PrinterPort 20.45.50.32 -PrinterHostAddress 20.45.50.32 "Adding printer port 20.45.50.32`n" 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`n" "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" "`nRemoving printer GOL Direct Print`n" Remove-PrinterPort 20.45.50.32 "Removing printer port 20.45.50.32`n" "Old printer has been removed, run the script again to install" } # 其他办公室的elseif逻辑继续保留 }
额外优化建议
- 可以将输入判断改为不区分大小写(比如
$office.ToLower() -eq 'quit'),提升用户操作容错性 - 原代码中
If ($office -eq 'gol' -or $install -eq 'add')的逻辑存在错误,应该使用-and,否则无论用户选择哪个办公室,只要输入'add'都会安装GOL的打印机,建议修正
内容的提问来源于stack exchange,提问作者ubercaw
相关产品推荐
相关产品推荐

