0
$array=@("blue","green","black")
[string]$input=Read-host "Input:"
$array[$input]

If I enter the number 1 into the input this gives no output. When I

Write-host $input

I get

System.Collections.ArrayList+ArrayListEnumeratorSimple

What I'm looking to do next is:

$inputlist=@("0")
$inputlist += $array[$input]

But I seem to end up with an array where each element is a single letter. I would like them to be one string in $inputlist[1].

1
  • Do you want the result to be 0, green or 0, g, r, e, e, n? $inputlist = @("0"); $inputlist += $array[$val] will already do the former. Commented May 25, 2015 at 13:44

1 Answer 1

1

$Input is an automatic variable and shouldn't be used in the way you do. Give your variable a different name and the problem will disappear:

PS C:\> $array = @('blue', 'green', 'black')
PS C:\> $val = Read-host 'Input'
Input: 2
PS C:\> $val
2
PS C:\> $val.GetType().FullName
System.String
PS C:\> $array[$val]
green

Splitting the string into an array of single characters can be handled by casting the string to a character array and then to a string array:

PS C:\> [string[]][char[]]$array[$val]
g
r
e
e
n

You'd still be able to append the characters to an array if you cast the string just to char[] (without casting it to string[] afterwards), but then you'd have an array with mixed types:

PS C:\> $inputList = @('0')
PS C:\> $inputList += [char[]]$array[$val]
PS C:\> $inputList
0
g
r
e
e
n
PS C:\> $inputList[0].GetType().FullName
System.String
PS C:\> $inputList[1].GetType().FullName
System.Char

If you want the entire string as the second element of the array, your existing code should already do that:

PS C:\> $inputList = @('0')
PS C:\> $inputList += $array[$val]
PS C:\> $inputList
0
green
Sign up to request clarification or add additional context in comments.

1 Comment

Thats great, it solved the first problem of the Write-host $input But i still have the issue of the $inputlist array storing each letter in single elements

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.