0

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.