Ralluhb Ralluhb - 3 months ago 25
PowerShell Question

Creating a Powershell menu from from config file

I have been trying to build a menu from a config file in Powershell. The purpose of the menu is to call other scripts and executables and to make maintenance easier so I can easily update the config whenever I need to add menu items.

Answer

First of all I strongly recommend you to use config files in XML format. Its REALLY much useful. I have came up with solution like this:

#Assuming this is content of your XML config file. You could easily add new Ids to insert new actions.
[xml]$Config=@"
<?xml version="1.0"?>
<Menu>
    <Actions>
        <Id>
            <Choice>1</Choice>
            <Script>C:\DoThis.ps1</Script>
            <Description>Will do this</Description>
        </Id>
        <Id>
            <Choice>2</Choice>
            <Script>C:\DoThat.ps1</Script>
            <Description>Will do that</Description>
        </Id>
    </Actions>
</Menu>
"@

#Here's the actual menu. You could add extra formating if you like.

$Message = ''
$Continue = $true    

DO 
{
    cls
    Write-Host 'Welcome to the menu!'
    Write-Host ''

    if ($Message -ne '')
    {
        Write-Host ''
    }

    foreach ($Item in @($Config.Menu.Actions.Id))
    {
        Write-Host ("{0}.`t{1}." -f $Item.Choice,$Item.Description)
    }
    Write-Host ''
    Write-Host "Q.`tQuit menu."
    Write-Host ''

    $Message = ''
    $Choice = Read-Host 'Select option'
    if ($Choice -eq 'Q'){$Continue = $false} #this will release script from DO/WHILE loop.

    $Selection = $Config.Menu.Actions.Id | ? {$_.Choice -eq $Choice}
    if ($Selection)
    {
        cls
        Write-Host ("Starting {0}" -f $Selection.Description)
        & $Selection.Script
        Write-Host ''
    }
    else
    {
        $Message = 'Unknown choice, try again'

    }
    if ($Continue)
    {
        if ($Message -ne '')
        {
            Write-Host $Message -BackgroundColor Black -ForegroundColor Red
        }
        Read-Host 'Hit any key to continue'
    }
    cls
}
WHILE ($Continue)
Write-Host 'Exited menu. Have a nice day.'
Write-Host ''

Output:

Welcome to the menu!

1.  Will do this.
2.  Will do that.

Q.  Quit menu.

Select option: 
Comments