[英]Displaying user inputs with powershell
say I have an array 说我有一个数组
$something = @(
"first",
"second"
)
how can I display this to the user as 我如何将其显示给用户
1. first
2. second
Selection :
I am able to do this by hash table and manually mapping 我可以通过哈希表和手动映射来做到这一点
@{
1="first"
2="second"
};
and doing the following 并执行以下操作
$something.Keys | sort |% { Write-Host $_ ")" $something.Item($_) }
[int32]$constuctPayload.Action = Read-Host
but if need to perform this using an array how can I do this. 但是如果需要使用数组执行此操作,该怎么做。 Ie looping over the item and displaying with index for user selection.
即遍历该项目并显示索引以供用户选择。 ?
?
You could use the IndexOf()
method, to find the index in the array. 您可以使用
IndexOf()
方法在数组中查找索引。
$something | ForEach-Object {Write-Host "$([Array]::IndexOf($something, $_)). $_ "}
Standard warning about being careful with Write-Host
. 关于警告
Write-Host
标准警告。 Also you might want to look into Out-GridView
. 另外,您可能需要查看
Out-GridView
。
Use a for
loop to iterate over the elements of the array and prepend each value with the index + 1. 使用
for
循环遍历数组的元素,并为每个值加上索引+ 1。
$something = 'first', 'second'
for ($i = 0; $i -lt $something.Count; $i++) {
Write-Host ('{0}. {1}' -f ($i+1), $something[$i])
}
[int32]$constuctPayload.Action = Read-Host -Prompt 'Selection'
I would recommend using the PromptForChoice()
method over Read-Host
, though: 我建议通过
Read-Host
使用PromptForChoice()
方法:
$something = '&first', '&second'
$title = 'The title.'
$msg = 'Selection?'
$choices = $something | ForEach-Object {
New-Object Management.Automation.Host.ChoiceDescription $_
}
$options = [Management.Automation.Host.ChoiceDescription[]] $choices
$default = 0
$constuctPayload.Action = $Host.UI.PromptForChoice($title, $msg, $options, $default)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.