Appending a string to each item of an array

17,762

Solution 1

Instead of a for loop you could also use the Foreach-Object cmdlet (if you prefer using the pipeline):

$str = "apple","lemon","toast" 
$str = $str | ForEach-Object {"Week$_"}

Output:

Weekapple
Weeklemon
Weektoast

Solution 2

Another option for PowerShell v4+

$str = $str.ForEach({ "Week" + $Week + $_ })

Solution 3

Something like this will work for prepending/appending text to each line in an array.

Set array $str:

$str = "apple","lemon","toast"

$str
apple
lemon
toast

Prepend text now:

for ($i=0; $i -lt $Str.Count; $i++) {
    $str[$i] = "yogurt" + $str[$i]
}

$str
yogurtapple
yogurtlemon
yogurttoast

This works for prepending/appending static text to each line. If you need to insert a changing variable this may require some modification. I would need to see more code in order to recommend something.

Share:
17,762

Related videos on Youtube

Riskworks
Author by

Riskworks

Updated on September 15, 2022

Comments

  • Riskworks
    Riskworks over 1 year

    I have an array and when I try to append a string to it the array converts to a single string.

    I have the following data in an array:

    $Str  
    451 CAR,-3 ,7 ,10 ,0 ,3 , 20 ,Over: 41  
    452 DEN «,40.5,0,7,0,14, 21 ,  Cover: 4  
    

    And I want to append the week of the game in this instance like this:

    $Str = "Week"+$Week+$Str 
    

    I get a single string:

    Week16101,NYG,42.5 ,3 ,10 ,3 ,3 , 19 ,Over 43 102,PHI,-  1,14,7,0,3, 24 ,  Cover 4 103,
    

    Of course I'd like the append to occur on each row.

  • Michael Timmerman
    Michael Timmerman about 7 years
    I do like this answer. It's simpler to read and better for one-off scenarios. However for a lengthier script where more control is required I think my answer is better suited. Just depends on the application.
  • Unnikrishnan
    Unnikrishnan almost 2 years
    I was searching for this kind of answer to add the same string to all the elements of an array!
  • Unnikrishnan
    Unnikrishnan almost 2 years
    I desire to know which is more PowerShell your answer or Martin Brandl's answer?