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
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With