8

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

J. Tam
  • 105
  • 1
  • 9

1 Answers1

9

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"
}
mklement0
  • 382,024
  • 64
  • 607
  • 775
ArcSet
  • 6,518
  • 1
  • 20
  • 34
  • Thanks! I was wondering if this would also apply to $(array[$i]) where $i is the variable declared by a for loop. – J. Tam Jul 25 '18 at 15:18
  • I answered your comment in the solution – ArcSet Jul 25 '18 at 15:22
  • @J.Tam answer your question from comment yourself `$array = @(2,3,5);for($i=0;$i -le 2;$i++){"I have $($array[$i]) apples"}` –  Jul 25 '18 at 16:58
  • For in-memory collections I suggest not recommending use of the pipeline, at least not without explaining the performance implications. – mklement0 Jul 25 '18 at 19:47
  • 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. – MostHated Feb 08 '21 at 20:40
  • @MostHated There is a performance hit when you use Linq because it has overhead. Here is a example...If I measure how long it takes to cycle through a array of 1000 objects. ForEach-Object takes 64 milliseconds, ForEach() takes 16 milliseconds and For() takes 2 milliseconds – ArcSet Feb 09 '21 at 21:10
  • Ah, I understand. While I should have, I didn't realize that using pipe methods like that would end up being Linq. Definitely glad that I do know that for sure now, so thanks. – MostHated Feb 11 '21 at 03:13