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



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

你永远不应该使用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)

最新更新