7

Example1:

Note 2: The comma is also used so separate items in an array {0,-30}

Example2:

To create an array, we create a variable and assign the array. Arrays are noted by the “@” symbol. Let’s take the discussion above and use an array to connect to multiple remote computers: $strComputers = @(“Server1″, “Server2″, “Server3″)

So, which one is correct or what is the difference ?

1
  • 1
    {0,-30} doesn't create an array, it creates a script block. It is, however, how an array it typically printed out in the host, as you can see if you run: New-Object PSObject -Property @{array='a','b','c'} Commented Jan 20, 2011 at 15:24

2 Answers 2

16

Example 2 uses the array cast syntax which allows a single element, for example, to be treated as an array:

$myList = @("Hello")

Essentially, it allows anything between the parenthesis to be treated as an array including the output from other commands:

$myArray = @(Get-Process Excel)

Alternatively you can just create an array by specifying a comma separated list:

$myArray = "hello", "world", "again"

(The curly brackets are not needed)

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

2 Comments

You should add the explanation that {} is a script block and not an array, to completely answer the question.
Also, @() is referred to as an array subexpression - Windows PowerShell in Action pg 119. :-). The second form above 'hello','world','again' is the "canonical" way to create an array. Array subexpression is typically used to ensure that the result of some expression is an array - either an empty, single element or multiple element array.
3

You can also attain a single element array by prepending the , operator to a single value:

[PS] C:\>$a = ,"Hello World"

[PS] C:\>$a.gettype()


IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array


[PS] C:\>$a.count

1

1 Comment

good point -- I edited it to indent the code so it shows as code (preformatted) instead of wrapping weird.

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.