Reputation: 282
I'm trying to create an "switch" statement that will have amount of choices based from the amount of returned objects.
First Example:
[array]$A1 = ("QWERTY", "ASDFGH")
so the "switch" function will look like this:
Switch ($Login = read-Host -Prompt Login) {
1 { $Login = "QWERTY" }
2 { $Login = "ASDFGH" }
}
Second Example:
[array]$A2 = ("A", "B", "C", "D")
so the "switch" function will look like this:
Switch ($Login = read-Host -Prompt Login) {
1 { $Login = "A" }
2 { $Login = "B" }
3 { $Login = "C" }
4 { $Login = "D" }
}
So i was thinking about some foreach loop to create simple string and then run command from string. I mange to do this, but I'm unable to run my generated string as command:
[array]$AR1 = ("QWERTY", "ASDFGH")
$q1 = "switch (Read-Host -Prompt Login) {"
$q2 = " }"
$Number = 0
$Script:ArrayFull = $null
$AR1 | % {
$_
$ArrayElement = $null
$NameOfTheLoginVariable = '$Script:User_Login'
$NumberOfArrayElements = $AR1.count
if ($NumberOfArrayElements -ne 0) {
$Number = $Number+1
$NumberOfArrayElements = $NumberOfArrayElements-1
$ArrayElement = "$Number { $NameOfTheLoginVariable = '$_' }"
$ArrayElement
$Script:ArrayFull += $ArrayElement
}
}
$SwitchCommand = $q1+$ArrayFull+$q2
$SwitchCommand = $SwitchCommand.ToString()
$Test1 = "switch (Read-Host) {1 { $Script:User_Login = 'QWERTY' }1 { $Script:User_Login = 'ASDFGH' } }"
#switch (Read-Host -Prompt Login) {1 { $Script:User_Login = 'QWERTY' }1 { $Script:User_Login = 'ASDFGH' } }
#& $Test1
& $SwitchCommand
But even if this code produce correct "Switch" statement as string, i can't execute it. Why ?
Anyway, this method is really ugly so maybe there is a better one ?
Upvotes: 0
Views: 5445
Reputation: 126842
Give this a try, enter a number between 1-4 when prompted:
[array]$a = "A", "B", "C", "D"
$login = read-host login
$switch = 'switch($login){'
for($i=1;$i -le $a.length; $i++)
{
$switch += "`n`t$i { '$($a[$i-1])'; break }"
}
$switch += "`n}"
Invoke-Expression $switch
Upvotes: 1
Reputation: 36738
While it is possible that with full context of the problem domain @Shay's solution may be necessary, the stated examples are simply asking for an array lookup so the same result may be achieved with this:
[array]$a = "A", "B", "C", "D"
[int]$login = read-host -prompt login
$selected = & {if ($login -ge 0 -and $login -lt $a.Length) { $a[$login-1] }}
So here again if you enter 2 you will get "B". Just as in the stated examples and in Shay's solution, if you enter a value out of bounds you do not get a returned value.
Upvotes: 2
Reputation: 68301
That switch statement is composed of script blocks. You can't just substitute a string for them.
You can use [scriptblock]::create() to create new script blocks from the string, but in this application I think I'd just work up an ordered hash table of script blocks. Then you have keys to present in the manu that will map to the script block that needs to run, and an array index to match to the number of choices you need to present.
Upvotes: 2