Tuesday, 31 January 2017

Working with Array in Powershell

Array holds a list of data items. The Powershell array items can be the same type or different types.

Create or Initialize an Empty Array

The following syntax just creates an empty array object.
$myArray = @()

Create Array with Items

We can easily create predefined Array by just setting comma separated elements.
$myArray = "A","B","Hello","World"
Using explicit syntax:
$myArray = @(1,2,3,4,5)

Add values to an Array

We can add items to an array object by using the + operator.
$myArray = @(1,2,3,4,5)
$myArray = $myArray + 6
You can simplify the add operation by using assignment operator.
$myArray += 6
You can also add another array object using + operator.
$myArray += $secondArray

Read the contents of an array

We need to specify index number to retrieve an element from array, The Powershell array elements starting at 0th index.

Display all the elements in an array:
$myArray
This command returns the first element in an array:
$myArray[0]
This command displays the 2nd,5th,8th elements
$myArray[1,4,7]
Return the range of elements (4th element to the 8th element):
$myArray[3..7]
Return the last element in an array:
$myArray[-1]

Contains check in array

If you want to find an array contains a certain value, you don’t have to iterate through elements to compare the values with search term. Instead, you can apply filter with various comparison operators directly to the array.
$myArray = "A","B","C","Hello","World"
This command would check and return the array elements contains the string "Worl".
$myArray -like "*Worl*"
This command would check if the first three array elements contains the string "B" and return values.
$myArray[0..2] -like "*B*"

Set or Update array values

Use the assignment operator (=) to change or update values in an array.
$myArray[2]=23

Sort an elements

You can simply sort the elements by using Sort operator.
$myArray = $myArray | Sort

Delete an array and elements

You can easily delete an entire array object by setting its value as null
$myArray = $null
But Arrays are fixed-size, so, you can not easily remove values at different indexes. For this need, you need to use System.Array or System.Collections.Generic.List.

Advertisements
Advertisements

No comments:

Post a Comment