I am having this below simple code to display menu in a script
Write-Host "=============Main Catagory================================="
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 Catagory================================="
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
}
Problem I am facing is when I am executing first time it is working fine. e.g. when I choose **1,2,3..**it is fine but when I am again going back from 3 to 1 as choice, the script is exiting and showing the powershell prompt.
Please let me know why it is happening. I may be not able to explain properly. please let me know if any question.
CodePudding user response:
Mathias R. Jessen gave you the pointer in his helpful comment, each menu / option should have their own function or script block and the logic should be wrapped in an infinite loop that ends when the Exit option is chosen.
I have reduced the code for demonstration purposes.
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' }
}
}