Primoz
Primoz

Reputation: 4331

What is correct syntax for arrays in powershell?

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 ?

Upvotes: 7

Views: 6933

Answers (2)

mjolinor
mjolinor

Reputation: 68273

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

Upvotes: 3

John Channing
John Channing

Reputation: 6591

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)

Upvotes: 16

Related Questions