harmonica141
harmonica141

Reputation: 1469

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?

Upvotes: 0

Views: 2650

Answers (2)

user6811411
user6811411

Reputation:

Just to show an alternative iterating the indices of the array

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

for($i=0;$i -lt $Strings.count;$i++) {
  $Strings[$i] += $Constant
}

$Strings

Sample output with '.\strings.txt' containing one,two,three

onesomestring
twosomestring
threesomestring

Upvotes: 1

Guenther Schmitz
Guenther Schmitz

Reputation: 1999

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

Upvotes: 1

Related Questions