8

I've written some pwsh code

"a:b;c:d;e:f".Split(";") | ForEach-Object { $_.Split(":") }
# => @(a, b, c, d, e, f)

but I want this

// in javascript
"a:b;c:d;e:f".split(";").map(str => str.split(":"))
[ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e', 'f' ] ]

a nested array

@(
    @(a, b),
    @(c, d),
    @(e, f),
)

Why? and what should I do

3 Answers 3

11

Use the unary form of ,, PowerShell's array-construction operator:

"a:b;c:d;e:f".Split(";") | ForEach-Object { , $_.Split(":") }

That way, the array returned by $_.Split(":") is effectively output as-is, as an array, instead of having its elements output one by one, which happens by default in a PowerShell pipeline.

, creates a - transient - wrapper array whose only element is the array you want to output. PowerShell then unwraps the wrapper array on output, passing the wrapped array through.

Sign up to request clarification or add additional context in comments.

Comments

0

With foreach-object, it's usually useful to unwrap the array:

ps | foreach modules | sort -u modulename

Comments

0

You can alternatively create also a stack or a queue. Below, I created with your array a stack.

$array = "a:b;c:d;e:f".Split(";")
$stack = New-Object -TypeName System.Collections.Stack
$array | ForEach-Object { $stack.Push($_.Split(":")) }

From here, the most used methods are .Push() to insert new items to your stack, .Peek() to use the first item of the stack and .Pop(), to retrieve and then remove the first item.

You mentioned that you wanted to create an array. This is also possible by using the ToArray() method.

$stackArray = $stack.ToArray()
$stackArray[2]
> a
> b

To keep in mind, creating a stack will inverse the order to the items.

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.