Home > Software engineering >  Combine Array with String
Combine Array with String

Time:07-02

I'm trying to combine an array with a string. But unfortunately it is not working like I want.

My code:

$split = -split $array
$mail = 'test_'
$domain = "@test.com"
ForEach-Object {$mail   $split   $domain}

My Output looks like this:

test_2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 [email protected]

What i need:

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
...

Can someone help me with my problem? Thank you!

CodePudding user response:

The ForEach-Object cmdlet requires pipeline input, which you're not providing (in its absence, the script block is called once, which means there is no point in using ForEach-Object at all).

Also, since you need per-element processing of your $split array, you must enumerate it, which the pipeline does for you automatically, as Jeroen Mostert's comment implies:

# Enumerate the elements of array $split, i.e. send
# its elements one by one to ForEach-Object, which sees each as $_
# Note: You can capture the results in a variable simply by 
#       uncommenting the next line:
# $emailAddresses = 
$split | ForEach-Object { $mail   $_   $domain }

Note the use of the automatic $_ variable, which refers to the current pipeline input object in each iteration.


However, with values already in memory it is more efficient to use the foreach statement:

# Note: You can capture the results in a variable simply by 
#       uncommenting the next line:
# $emailAddresses = 
foreach ($index in $split) { $mail   $index   $domain }

Note the need to specify the input as part of the (...) expression, and the need to name a self-chosen enumeration (iterator) variable.


Finally, a concise and efficient but somewhat obscure solution is to use the regex-based -replace operator:

# Note: You can capture the results in a variable simply by 
#       uncommenting the next line:
# $emailAddresses = 
$split -replace '^', $mail -replace '$', $domain

This relies on -replace being able to operate on arrays as input, in which case the replacement operation is performed on each element, resulting in a transformed array as output.

Regex ^ matches the start of a string, $ matches the end, so that the two operations effectively prepend / append the value of $mail / $domain to each element of $split.

CodePudding user response:

And you can user variable for pipelines in mklements0's solution:

$elements = $split | ForEach-Object { $mail   $_   $domain }
# [email protected]
Write-Host $elements[3]
  • Related