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]

`

BrandyPuff
  • 11
  • 2
  • 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. – Abraham Zinala Jun 12 '22 at 04:40

1 Answers1

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.

alfi
  • 31
  • 4
  • Thank you so much, this was driving me crazy! I'm still learning the idiosyncrasies of Powershell. – BrandyPuff Jun 12 '22 at 13:45
  • 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. – mklement0 Jun 12 '22 at 22:25