Another solution, which is fast and concise, albeit a bit obscure.
It uses the regex-based -replace
operator with regex '^'
which matches the position at the start of each input string and therefore effectively prepends the replacement string to each array element (analogously, you could use '$'
to append):
# Sample array.
$array = 'one', 'two', 'three'
# Prepend 'Week ' to each element and create a new array.
$newArray = $array -replace '^', 'Week '
$newArray
then contains 'Week one', 'Week two', 'Week three'
To show an equivalent foreach
solution, which is syntactically simpler than a for
solution (but, like the -replace
solution above, invariably creates a new array):
[array] $newArray = foreach ($element in $array) { 'Week ' + $element }
Note: The [array]
cast is needed to ensure that the result is always an array; without it, if the input array happens to contain just one element, PowerShell would assign the modified copy of that element as-is to $newArray
; that is, no array would be created.
As for what you tried:
"Week"+$Week+$Str
Because the LHS of the +
operation is a single string, simple string concatenation takes place, which means that the array in $str
is stringified, which by default concatenates the (stringified) elements with a space character.
A simplified example:
PS> 'foo: ' + ('bar', 'baz')
foo: bar baz
Solution options:
For per-element operations on an array, you need one of the following:
A loop statement, such as foreach
or for
.
- Michael Timmerman's answer shows a
for
solution, which - while syntactically more cumbersome than a foreach
solution - has the advantage of updating the array in place.
A pipeline that performs per-element processing via the ForEach-Object
cmdlet, as shown in Martin Brandl's answer.
An expression that uses the .ForEach()
array method, as shown in Patrick Meinecke's answer.
An expression that uses an operator that accepts arrays as its LHS operand and then operates on each element, such as the -replace
solution shown above.
Tradeoffs:
Speed:
- An operator-based solution is fastest, followed by
for
/ foreach
, .ForEach()
, and, the slowest option, ForEach-Object
.
Memory use:
- Only the
for
option with indexed access to the array elements allows in-place updating of the input array; all other methods create a new array.[1]
[1] Strictly speaking, what .ForEach()
returns isn't a .NET array, but a collection of type [System.Collections.ObjectModel.Collection[psobject]]
, but the difference usually doesn't matter in PowerShell.