Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting an array value into a string in powershell [duplicate]

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

like image 716
J. Tam Avatar asked Mar 12 '26 07:03

J. Tam


1 Answers

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"
}
like image 99
ArcSet Avatar answered Mar 14 '26 23:03

ArcSet