Create show-menu in powershell depending on variab

2019-07-11 21:46发布

问题:

I want to create a menu with show-menu that will depend on what is present on the computer.

I want to list in the menu usernames available on c:\users\ (based on the folders names).

For example : in c:\users there is folder nammed :

homer.simpson
lisa.simpson
bart.simpson

and with show-menu ask the user to choose one of them by typing 1 for homer.simpson 2 for lisa.simpson etc ..

How can i do it ?

Thank you in advance !

EDIT : Code

$users = Get-ChildItem "$env:SystemDrive\Users"| ForEach-Object { $_.Name }

foreach ($user in $user)   {

$user
$num++ 

New-Variable -Name "a$num" -Value $user
#Get-Variable -Name "$user$i" 

}



function Show-Menu
{
     param (
           [string]$Title = 'Please select an user'
     )
     cls
     Write-Host "================ $Title ================"

     Write-Host "1: $a1"
     Write-Host "2: $a2"
     Write-Host "3: $a3"
     Write-Host "Q: $a4"
}


do
{
     Show-Menu
     $input = Read-Host "Please make a selection"
     switch ($input)
     {
           '1' {
                cls
                'You chose option #1'
           } '2' {
                cls
                'You chose option #2'
           } '3' {
                cls
                'You chose option #3'
           } 'q' {
                return
           }
     }
     pause
}
until ($input -eq 'q')

回答1:

Try this (based on Show-Menu by Adam Bertram):

function Show-Menu
{
    param (
        [string]$Title = 'My Menu'
    )
    Clear-Host
    Write-Host "================ $Title ================"

    $Menu = @{}

    (Get-ChildItem C:\Users).Name | ForEach-Object -Begin {$i = 1} { 

        Write-Host "$_`: Press '$i' for this option." 
        $Menu.add("$i",$_)
        $i++
    }

    Write-Host "Q: Press 'Q' to quit."

    $Selection = Read-Host "Please make a selection"

    if ($Selection -eq 'Q') { Return } Else { $Menu.$Selection }

}

$UserSelection = Show-Menu -Title 'Local Users'

Per the comments, uses (Get-ChildItem C:\Users).Name to get the list of user folder names. These are then piped to a ForEach-Object loop which starts by initilizing a counter variable $i as 1.

In the loop it prints out the name of each file (now represented as $_ which is the automatic variable for the current item in the pipeline) and uses the counter variable to display the numbered options. It also puts each number/name pair in a hashtable named $Menu which is then used as a lookup when the selection is entered via Read-Host.

The selected option is returned to the $UserSelection variable.