1

So, I have no seen anything remotely helpful on google or SO about this.

I have an array of strings and I want to run -split on each string in the array and end up with an array containing arrays of strings.

However when I do this:

$Strings | % { $_ -split ($Sep) }

PS flattens the result and I end up with an array of strings containing the concatenated result of every -split.

E.g. For this

$Strings = @("a b c", "d e f")
$Sep = " "
$Strings | % { $_ -split ($Sep) } 

I get @("a", "b", "c", "d", "e", "f") but I want @( @("a", "b", "c"), @("d", "e", "f") ). What exactly am I not doing right?

1
  • 1
    Wrap each resulting string array in another$Strings | % { ,@($_ -split $Sep) } Commented Nov 6, 2024 at 13:16

1 Answer 1

3

You can either use the , comma operator:

In expression mode, as a unary operator, the comma creates an array with just one member.

$Strings = @('a b c', 'd e f')
$Sep = ' '
$result = $Strings | ForEach-Object { , ($_ -split $Sep) }
$result[0]
# a
# b
# c
$result[1]
# d
# e
# f

Or Write-Output -NoEnumerate:

The NoEnumerate parameter suppresses the default behavior, and prevents Write-Output from enumerating output.

$Strings = @('a b c', 'd e f')
$Sep = ' '
$result = $Strings | ForEach-Object { Write-Output ($_ -split $Sep) -NoEnumerate }
$result[0]
# a
# b
# c
$result[1]
# d
# e
# f

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.