菜单选择不能按选择返回



我有下面这个简单的代码来显示一个脚本菜单

Write-Host "============= Main Category ================================="
Write-Host " '1' InfoBlox"
Write-Host " '2' Installation"
Write-Host " '3' Active Directory"
Write-Host " '4' LogInventory"
Write-Host " '5' Configuration"
Write-Host " '6' New Server Build CMDB Update "
Write-Host " '7' for Exit"
Write-Host "========================================================"
$choice = Read-Host "`nEnter Choice"
if($choice -eq '1')
{
#Menu for choice 
cls
Write-Host "=============InfoBlox================================="
Write-Host " '1' Add CNAME record"
Write-Host " '2' Delete CNAME record"
Write-Host " '3' Add A-record and PTR record"
Write-Host " '4' Delete A-record and PTR record"
Write-Host " '5' for Main Menu"
Write-Host "========================================================"
$subchoice = Read-Host "`nEnter Choice"
#code here
if($subchoice -eq '5')
{
cls
Write-Host "============= Main Category ================================="
Write-Host " '1' InfoBlox"
Write-Host " '2' Installation"
Write-Host " '3' Active Directory"
Write-Host " '4' LogInventory"
Write-Host " '5' Configuration"
Write-Host " '6' New Server Build CMDB Update "
Write-Host " '7' for Exit"
Write-Host "========================================================"
$choice = Read-Host "`nEnter Choice"
}
if($choice -eq '2')
{
#code here
}
if($choice -eq '3')
{
#code here
}

我面临的问题是,当我第一次执行它的工作很好。例如,当我选择**1,2,3…**它很好,但当我再次从3返回到1时作为选项,脚本退出并显示powershell提示符。

请告诉我为什么会这样。我可能解释不清楚。如果有任何问题,请告诉我。

Mathias R. Jessen在他的有用评论中给了你一个指针,每个菜单/选项都应该有自己的函数或脚本块,逻辑应该包装在一个无限循环中,当退出时结束

为了演示,我已经缩减了代码。

function Menu {
Write-Host " '1' Option 1"
Write-Host " '2' Option 2"
Write-Host " '3' for Exit"
}
function SelectSomething {
Read-Host "`nEnter Choice"
}
function FirstOption {
Write-Host " '1' Add CNAME record"
Write-Host " '2' Delete CNAME record"
Write-Host " '3' for Main Menu"
SelectSomething
}
function SecondOption {
Write-Host " '1' InfoBlox"
Write-Host " '2' Installation"
Write-Host " '3' for Main Menu"
SelectSomething
}
$firstScriptblock = {
switch(FirstOption) {
1 { 'Option 1 - Add CNAME record' }
2 { 'Option 2 - Delete CNAME record' }
3 { return }
Default { Write-Warning 'Invalid Selection' }
}
$Host.UI.ReadLine()
& $MyInvocation.MyCommand.ScriptBlock
}
$secondOption = {
Write-Warning 'Not implemented! Back to Menu'
$Host.UI.ReadLine()
}
:outer while($true) {
Clear-Host
Menu
switch(SelectSomething) {
1 { & $firstScriptblock }
2 { & $secondOption }
3 { break outer }
Default { Write-Warning 'Invalid Selection' }
}
}

最新更新