我一直在尝试从Powershell中的配置文件构建菜单。菜单的目的是调用其他脚本和可执行文件,并使维护更容易,这样我就可以在需要添加菜单项时轻松地更新配置。
首先,我强烈建议您使用XML格式的配置文件。它真的很有用。我想出了这样的解决方案:
#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 ''
输出:
Welcome to the menu!
1. Will do this.
2. Will do that.
Q. Quit menu.
Select option: