0

I have following issue:

I have a string, like $word ='ABC.DEF.GHI'

I want to split this String into an array at the dot and add a string instead. Desired outcome would be like:

$arrayWordSplitted = 'ABC 123; DEF 123; GHI 123'

with $arrayWordSplitted[0] = 'ABC 123'

I tried the .split()- Method but I can't add for every element with this.

I tried something like this:$wordSplitted = $word.split('.') + '123'

But I get $wordSplitted='ABC; DEF; GHI; 123

How to split and add for all elements in powershell?

2 Answers 2

1

I guess you're looking for that :

$wordSplitted=$word.split('.') | %{ $_ += ' 123' ; $_ }

Some details: $word.split('.') produces a string array with words, string array that we pass through a pipe (|) to an elements iterator ( %{ }). In this iterator, we add to the string element ($_) the string ' 123' and then send it back as an output with ; $_. Thus, PowerShell build an array of strings with all strings suffixed with ' 123' and stores it in $wordSplitted.

EDIT: You can reduce it like @Olaf has done it with :

$wordSplitted=$word.split('.') | %{ $_ + ' 123' }
Sign up to request clarification or add additional context in comments.

Comments

1

A little more verbose version would be something like this:

$word = 'ABC.DEF.GHI' 
$SplittedWord = $word -split '\.'
$AddedStrings = $SplittedWord | ForEach-Object {$_ + ' 123'}

If you want to re-join them ...

$arrayWordSplitted = $AddedStrings -join '; '

And the output would be:

ABC 123; DEF 123; GHI 123

1 Comment

Thank you very much! Really appreciate it! It works for me

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.