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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句