Home > Software design >  Powershell: I am trying to create an array from looping and put it into variable
Powershell: I am trying to create an array from looping and put it into variable

Time:10-11

Here my example code:

$old = @("a_1","b_2","c_3","d_4","e_5")
foreach ($f in $old)
{
$spl = "$f".Split("_")
$spl[0]
}

Output is as expected array of 'a', 'b','c','d','e'. But I want to declare it to a variable so I can use it as new list for another foreach loop. If I try:

foreach ($f in $old)
{
$spl = "$f".Split("_")
$ls = $spl[0]
}
$ls

the output is just 'e'. Any ideas ?

CodePudding user response:

You can assign the entire output stream from the foreach loop to $ls like this:

$old = @("a_1","b_2","c_3","d_4","e_5")

$ls = foreach ($f in $old)
{
  $spl = "$f".Split("_")
  $spl[0]
}
  • Related