Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 848
Primoz Avatar asked Jan 19 '11 14:01

Primoz


People also ask

How do you write an array in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.

What is an array syntax?

Array declaration syntax is very simple. The syntax is the same as for a normal variable declaration except the variable name should be followed by subscripts to specify the size of each dimension of the array. The general form for an array declaration would be: VariableType varName[dim1, dim2, ...

Do PowerShell arrays start at 0 or 1?

A common programming error is created because arrays start at index 0. Off-by-one errors can be introduced in two ways.


Video Answer


1 Answers

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)

like image 199
John Channing Avatar answered Sep 19 '22 19:09

John Channing