5

Sometimes PowerShell is completely awesome and other times it is completely frustrating and unintuitive. It is almost always an array that is causing me grief.

This time I have an array of strings. I want to split each string on white space so that I end up with an array of arrays of strings. I have tried this:

$data | ForEach-Object { $_.Split(@(), [System.StringSplitOptions]::RemoveEmptyEntries) }

But that just flattens everything into one large array of strings like SelectMany in C#. I have also tried this:

$data | Select-Object { $_.Split(@(), [System.StringSplitOptions]::RemoveEmptyEntries) }

But that gives me an array of PsCustomObject. I feel like this should be incredibly easy. Am I missing something completely obvious?

2
  • 1
    $data | ForEach-Object { ,$_.Split(@(), [System.StringSplitOptions]::RemoveEmptyEntries) } Commented Aug 27, 2015 at 18:13
  • @PetSerAl - Of course, why didn't I think of that /s. You should add that as an answer. Commented Aug 27, 2015 at 19:39

2 Answers 2

4

You can put unary comma (array) operator to prevent PowerShell to enumerate an array, returned by Split method:

$data | ForEach-Object { ,$_.Split(@(), [System.StringSplitOptions]::RemoveEmptyEntries) }
Sign up to request clarification or add additional context in comments.

Comments

2

How about this? What I do here is I loop through all of the elements in the array, and then I do the split and replace the current item with the returned String[] from the Split():

$Outer = "hello there", "how are you?", "I'm good, thanks"

for ($i = 0; $i -lt $Outer.Count; $i++) {
    $Outer[$i] = $Outer[$i].Split(" ")
}

$Outer[1][2]
# you?

$Outer[2][0]
# I'm

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.