1
$nameonly =  @("") * 20 

$i=1 
do 
{
    $nameonly[$i] = "A$i" 
    $i++
}
until ($i -eq 10)

write-host "$nameonly[4]"

When i run the code i expect the output to be: A4 but instead i get:

A1 A2 A3 A4 A5 A6 A7 A8 A9 [4]

`

1
  • 3
    PowerShell stops the parsing of expressive tokens such as the [..] in a string. The way around that, you wrap the expression inside the string with a sub-expression operator $(..). Switch "$nameonly[4]", to this "$($nameonly[4])". You can also just leave out the quotes. Commented Jun 12, 2022 at 4:40

1 Answer 1

2

Try removing the quotation marks in your final command. So it should be write-host $nameonly[4] This will get you the indexed value in position 4 of the array.

You can also skip the write-host command. Invoking the variable $nameonly[4] will output to the console.

If you use quotation marks then it will convert the whole array into a string and output the entire array content as a string object.

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

2 Comments

Thank you so much, this was driving me crazy! I'm still learning the idiosyncrasies of Powershell.
Good advice, but note that the only problem with BrandyPuff's attempt was neglecting to enclose the expression $nameonly[4] in $(...) inside "..." - see the linked duplicate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.