PowerShell: How to Append String to Each Item in Array


Often you may want to append a string to each item in an array in PowerShell.

You can use the following syntax to do so:

$teams = $teams.ForEach({ "Team" + $_ })

This particular example appends the string “Team” to the beginning of each item in the existing array named $teams.

Note that the ForEach command allows us to perform a task on each item in an array.

We then use the plus sign ( + ) to concatenate a specific string to the existing ( $_ ) item in the array.

The following example shows how to use this syntax in practice.

Example: How to Append String to Each Item in Array in PowerShell

Suppose that we create an array named $teams that contains the names of various basketball teams:

$teams = @("Mavs", "Nets", "Hawks", "Spurs")

We can use the following syntax to append the string “Team” to each item in the array:

$teams = $teams.ForEach({ "Team" + $_ })

The following screenshot shows how to use this syntax in practice:

PowerShell append string to each item in array

Notice that when we view the $teams array again we can see that the string “Team” has been appended to each item in the array.

Note that we could also use the following syntax to add the string “Teams” to the end of each item in the array:

$teams = $teams.ForEach({ $_ + "Team" })

The following screenshot shows how to use this syntax in practice:

PowerShell append string to end of each item in array

Notice that when we view the $teams array again we can see that the string “Team” has been appended to the end of each existing item in the array.

Note: You can find the complete documentation for the ForEach command in in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if Input Value Exists in Array
PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply