2

In the following Powershell statements, why do I need the comma to instantiate a .Net array list or stack from the Powershell Object[]?

$list = "A","B","C"
$stack = New-Object System.Collections.Stack(,$list)

Why do I need it and what does the comma mean?

2 Answers 2

5

The comma is an array operator in PowerShell.

The problem is PowerShell is unwrapping your array into arguments for the overload. Adding a comma is keeping it as an array.

Without the comma you get this error:

New-Object : Cannot find an overload for "Stack" and the argument count: "3".

From Windows PowerShell in Action (Second Edition): The comma operator always wraps its argument value in a new one-element array.

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

2 Comments

Ah HA! What an interesting feature of powershell. Thanks it makes sense.
@Ashwin I removed the alternative you added, I'm afraid it doesn't work. @(@(@(1))) is no different than @(1).
3

If you try to pass $list to the constructor directly, you get this error:

PS C:\Users\Svick> New-Object System.Collections.Stack $list
New-Object : Cannot find an overload for "Stack" and the argument count: "3".

I think this explains what's going on: PowerShell treats each item in the array as an argument to the constructor. If you want to put them all into one parameter, you need to enclose the array in another array.

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.