0

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. I.e looping over the item and displaying with index for user selection. ?

2 Answers 2

1

You could use the IndexOf() method, to find the index in the array.

$something | ForEach-Object {Write-Host "$([Array]::IndexOf($something, $_)). $_ "}

Standard warning about being careful with Write-Host. Also you might want to look into Out-GridView.

Sign up to request clarification or add additional context in comments.

Comments

1

Use a for loop to iterate over the elements of the array and prepend each value with the index + 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:

$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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.