PowerShell Array

 Array in PowerShell



The array is a type of data structure that can be used to 
store a collection of items, the collection of items can 
be either of the same datatype or different. 

The elements in an array can be accessed using 
the index. The index of the array usually starts at 0 just 
like other programming languages, so to access the first element, use index [0]. 

Define Array in PowerShell


Array in PowerShell can be defined in multiple 

ways.

  1. To create and initialize an array, assign comma separated multiple values to a variable. 
  2. Pass values to variable within bracket  beginning with @ like $var = @()


When no data type is specified, PowerShell creates each array as an object array (System.Object[]).


    3. We can create array to hold value of specific type also, like below



How to access an Array


We can refer to an array by using its variable name. To display all the elements in the array, type the array name.


We can also refer to the elements in an array by using an index, beginning at position 0. Enclose the index number in brackets. For example, to display the first element in the $arrayvar2 array


We can also get part of array using range operator, like below:
$arrayvar2[0..2] return first to third element from array.

Operations on Array



To get the properties and methods of an array, such as the Length property and the SetValue method, use the InputObject parameter of the Get-Member cmdlet.


Get element count of Array

Get how many values are stored in array, use Length or its alias property Count.



Add element to Array

We can add new values to array using “+=“ operator, Like below

Update element of Array

We can update elements of array using index. Like below

Sorting of Array elements

sort operator can be used to sort the elements of an array

Looping over Array elements

for and foreach loop can be used to iterate over array.


For Video: 



Comments

Popular Posts

How to Import and Export Delimited Files, like CSV, in PowerShell

PowerShell Arithmetic Operators

How to generate a GUID in PowerShell