简体   繁体   中英

How can I define a variable in Powershell with value from selection?

I've tried to use the function Out-Menu for playing around with PowerShell. So far it works but now I wonder how I can create a variable based on the users selection. If I have an array $colors = 'blue', 'white', 'red' and provided the user selects 1. blue from the resulting list. How can I get his selection "blue" into a variable let's say $uChoice ?

$color = Read-Host -Prompt "Please enter the color (blue, white, red) !"
Write-host "Color is: " $color  
If ($color -eq "blue") {
    $country = 'Germany'
} elseif ($color -eq "white") {
    $country = 'United Kingdom'
} elseif ($color -eq "red") {
    $country = 'France'
} else {
    Write-host -ForegroundColor Red "Unknown color - please check your input !"
    exit
}
# So now I can continue with $country

Since you are keen to learn I leave you something for you :) Lots of new concepts for you to learn here:

Remove-Variable userChoice, country -ErrorAction SilentlyContinue
Clear-Host

while(-not $country)
{
    try
    {
        [validateset('blue','white','red')]
        $userChoice = Read-Host -Prompt "Please enter the color (blue, white, red) !"

        $country = switch($userChoice)
        {
            blue {'Germany'}
            white {'United Kingdom'}
            red {'France'}
        }

        Write-Host -ForegroundColor $userChoice "Choice was: $country"
    }
    catch
    {
        Write-Host -ForegroundColor Red "Unknown color - please check your input !"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM