3

Is there a difference between these two array creation statements? So, is '@' sign optional when creating arrays?

$a = "This", "Is", "a", "cat"
$a.GetType()
$a | gm
$a = @("This", "Is", "a", "cat")
$a.GetType()
$a | gm

2 Answers 2

6
$a = @() # declare an empty array.

$a = @(mysingleitem) # declare an array with a single element

In other case is optional.

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

1 Comment

Similarly, if the results of the expression inside the array subexpression operator evaluates to null or a single item, then it will still return an array of length zero or one, respectively. E.g. @(Get-WMIObject win32_logicalDisk), from about_Operators.
2

Is there a difference between these two array creation statements?

Though I am not 100% sure (it depends on PowerShell guts) the difference may be the following: "This", "Is", "a", "cat" creates an array. @("This", "Is", "a", "cat") creates the same array and then applies the operator @() to it (apparently redundant operation in this particular case).

Using, for example, this profiler we can see that the second expression is quite slower (14% or something), so that my guess may be correct. Ideally, PowerShell code interpretator could treat these two expressions in the same way but it probably does not.

See also the help topic (the end, about operators @() and ,)

help about_operators

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.