12

I was having difficulty understanding how String values work with arrays in powershell. I wanted to know the correct syntax for placing an array into a string. Currently, this is what I am trying. The square brackets seem to be registered as part of the string rather than the variable.

$array = @(2,3,5)

$string = " I have $array[2] apples"

This outputs: I have 2 3 5[2] apples

2
  • 1
    Use $($array[2]) the $() runs whatever is inside as powershell Commented Jul 25, 2018 at 15:13
  • 1
    There's also the -f operator; e.g.: "I have {0} apples" -f $array[2] Commented Jul 25, 2018 at 16:59

1 Answer 1

14

The [2] is being read as a string. Use $($array[2]) in order to run that part as powershell.

$array = @(2,3,5)

"I have $($array[2]) apples"

This outputs I have 5 apples.

In the comments you asked how to do a for loop for this.

In powershell you should pipe whenever you can, the pipe command is |

@(2,3,5) | foreach-object{
    "I have $_ apples"
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! I was wondering if this would also apply to $(array[$i]) where $i is the variable declared by a for loop.
I answered your comment in the solution
@J.Tam answer your question from comment yourself $array = @(2,3,5);for($i=0;$i -le 2;$i++){"I have $($array[$i]) apples"}
For in-memory collections I suggest not recommending use of the pipeline, at least not without explaining the performance implications.
I know this is pretty old, but what might those performance implications be? I typically use C#, but am doing some PowerShell right now and was about to just do a for loop as I normally would, but came across this answer and was going to use the above "PowerShell way" and pipe it, but then I saw this comment, and now I don't know what I should use.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.