Search code examples
arraysstringpowershellstring-concatenation

Simple string concatenation updating array in Powershell


I have an array of strings in Powershell. For each element I want to concatenate a constant string with the element and update the array at the corresponding index. The file I am importing is a list of non-whitespace string elements separated by line breaks.

The concatenation updating the array elements does not seem to take place.

$Constant = "somestring"
[String[]]$Strings = Get-Content ".\strings.txt"

foreach ($Element in $Strings) {
  $Element = "$Element$Constant"
}

$Strings

leads to the following output:

Element
Element
...

Following the hint of arrays being immutable in Powershell I tried creating a new array with the concatenated values. Same result.

What do I miss here?


Solution

  • you concatenate the values to the local variable $Element but this does not change the variable $Strings

    here is my approach, saving the new values to $ConcateStrings. by returning the concatenated string and not assigning it to a local variable the variable $ConcateStrings will have all the new values

    $Constant = "somestring"
    $Strings = Get-Content ".\strings.txt"
    
    $ConcateStrings = foreach ($Element in $Strings) {
        "$Element$Constant"
    }
    
    $ConcateStrings