Functions/Show-SubMenu.ps1

function Show-SubMenu
{
<#
.Synopsis
    Show a sub-menu and keep it running until an item returns "exit".
.DESCRIPTION
    Wraps Show-Menu so that the sub-menu stays on screen after each action,
    just like the main menu does. The loop only ends when a menu item's
    Action scriptblock returns the string "exit" (case-insensitive).
 
    This means "Back" / "Return" items in a sub-menu simply need to do:
        Action = { "exit" }
    …and Show-SubMenu will return control to the caller (typically the
    parent menu's action scriptblock), which then allows the parent menu's
    own while-loop to redraw itself.
 
    Any non-"exit" return value is written to the pipeline so callers can
    still capture results:
        $picked = Show-SubMenu -MenuName "ColorPicker"
 
.PARAMETER MenuName
    The Name of the sub-menu to display (as set with New-Menu -Name).
 
.PARAMETER Force
    Passed through to Show-Menu to suppress confirmation prompts.
 
.EXAMPLE
    # "Back" item – just return "exit"
    $backItem = New-MenuItem -Name "Back" -DisplayName "< Back" -DisableConfirm -Action { "exit" }
 
    # Parent menu item that opens the sub-menu and waits for it to finish
    $openSub = New-MenuItem -Name "OpenSub" -DisplayName "Open Sub-Menu" -DisableConfirm -Action {
        $result = Show-SubMenu -MenuName "MySubMenu"
        # $result holds the last non-exit return value, if any
    }
 
.NOTES
    NAME: Show-SubMenu
    KEYWORDS: General scripting Controller Menu
#>

    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory)]
        [string]
        $MenuName
        ,
        [switch]
        $Force
    )

    $lastResult = $null
    $menuObj = Get-Menu -Name $MenuName
    $IsMainMenu = $menuObj.IsMainMenu -eq $true

    while ($true)
    {
        $result = Show-Menu -MenuName $MenuName -Force:$Force -LastResult $lastResult


        $lastResult = $result

        if ($result -is [PSCustomObject] -and $result.menu)
        {
            if ($result.menu -eq "back" -and -not $IsMainMenu) { 
                $result.menu = "this"
                break
            }
            if ($result.menu -eq "main" -and -not $IsMainMenu) { break }
            if ($result.menu -eq "exit") { exit }
        }
    }

    Write-Output $lastResult
}