PowerShell 中的 Switch 语句和复制粘贴采用最后一个数组输出而不是示例第一个

Switch statement in PowerShell and copy paste takes last array output and not example first one

PowerShell 中的 switch 语句有问题,不知道为什么会发生。

出于某种原因,我想根据开关复制内容,当我从开关 A

粘贴时,我只得到最后的输出,如 "D"

知道如何继续让它在 PowerShell 4.0 中运行吗?我仅限于 4.0,因为我的学校不会在服务器上升级到 PowerShell 5。

[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 { '$($test = $a[$i-1])  $([System.Windows.Clipboard]::SetText($test))'; break }" 
}

$switch += "`n}"

Invoke-Expression $switch

You should never use Invoke-Expression。听起来你真正想要的是哈希表或类似的:

# added to reference the System.Windows namespace
Add-Type -AssemblyName PresentationFramework

$options = @{
    A = 'this thing'
    B = 'That thing'
    C = 'Another thing'
    D = 'Oh look over here'
}

$login = Read-Host -Prompt login

[Windows.Clipboard]::SetText($options[$login])

为了更进一步,我建议验证输入:

do {
    $login = Read-Host -Prompt login
} until ($options.Keys -contains $login)