Put the switch tests inside of the while loop and use it to validate the user input. Also put the submenu in it's own function.
[BOOLEAN]$global:xExitSession = $false
Function LoadMenuSystem() {
[INT]$xMenu1 = 0
[INT]$xMenu2 = 0
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUserDeclaredVarsMoreThanAssignments', '', Scope = 'Function')]
[BOOLEAN]$xValidSelection = $false
$Loop = $true
while ( $Loop) {
Clear-Host
Write-Host "`n"
Write-Host "PLEASE SELECT TOOL TO LAUNCH:`n" -ForegroundColor Yellow
Write-Host "`[1] Tool #1"
Write-Host "`[2] Tool #2"
Write-Host "`[3] Tool #3 and sub-options [...]" # Sub-menu
Write-Host "`[9] Exit"
try {[int]$xMenu1 = Read-host "`n`Please enter option 1 to 3..."} catch {}
$ShowMsg = $true # Default to show the completed message
Switch ($xMenu1) {
1 {
Write-Host "Tool #1 launched..." -ForegroundColor Yellow
}
2 {
Write-Host "Tool #2 launched..." -ForegroundColor Yellow
}
3 {
Tool3Menu # Show the sub-menu
$ShowMsg = $false # Don't display the complete message
}
9 {
$Loop = $false
}
default {
Write-Host "`nPlease select one of the options available.`n" -ForegroundColor Red
Start-Sleep -Seconds 1
$ShowMsg = $false # Don't display completed message
}
}
if ($Loop -and $ShowMsg) {
write-host "`n`n################################## COMPLETED ##################################`n" -ForegroundColor Yellow
Read-Host "Press any key to go back to option..."
}
}
}
Function Tool3Menu {
$Loop3 = $True
while ( $Loop3 ) {
Clear-Host
Write-Host "Tool-Sub-Menu:`n" -ForegroundColor Yellow
Write-Host "`[1] Sub-Tool #1"
Write-Host "`[2] Sub-Tool #2"
Write-Host "`[3] Return to main options [...]"
try {[int]$xMenu2 = Read-host "`n`Please enter option 1 to 3..."} catch {}
$ShowMsg3 = $True # Default to show the completed message
Switch ($xMenu2) {
1 {
Write-Host "Tool #3 Sub-option #1..." -ForegroundColor Yellow
}
2 {
Write-Host "Tool #3 Sub-option #2..." -ForegroundColor Yellow
}
3 {
$Loop3 = $False
}
default {
Write-Host "`nPlease select one of the sub-options available.`n" -ForegroundColor Red
Start-Sleep -Seconds 1
$ShowMsg3 = $False # Don't display completed message
}
}
if ($Loop3 -and $ShowMsg3 ) { # did user ask to go back
write-host "`n`n################################## SUB ITEM COMPLETED ##################################`n" -ForegroundColor Yellow
Read-Host "Press any key to return to submenu..."
}
}
}
# Launch main menu
LoadMenuSystem