The -replace
operator allows for a concise and efficient solution for string arrays:
# Returns array @('test-api', 'test-asp', 'test-appi')
"-api", "-asp", "-appi" -replace '^', 'test'
-replace
is regex-based and accepts arrays as input, in which case the operation is performed on each element.
^
matches the position at the beginning of the string, at which the substitution string, 'test'
is inserted, in effect prepending that string to each array element (by contrast, $
matches the end of each string and can be used to append a value).
For other data types and if you need more flexibility, you can use the .ForEach()
array method (which, in the case of a collection that is already in memory, is faster than the ForEach-Object
cmdlet):
("-api", "-asp", "-appi").ForEach({ 'test' + $_ })
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.
If you do need an actual array, you can simply cast the result:
# Use the appropriate data type, or simply [array] for an [object[]] array.
[string[]] ("-api", "-asp", "-appi").ForEach({ 'test' + $_ })