Reputation: 7029
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?
Upvotes: 5
Views: 184
Reputation: 22102
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) }
Upvotes: 4
Reputation: 5862
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
Upvotes: 2