How to Get the First Element of an Array in PowerShell?

When working with arrays in PowerShell, I got a requirement to retrieve the first element. In this PowerShell tutorial, I will explain how to get the first element of an array using PowerShell.

In PowerShell, to obtain the first element of an array, simply use the index 0 with the array variable. For instance, if $array is your array, $array[0] will retrieve the first item. This is a straightforward approach as PowerShell arrays are zero-indexed, where the first element is always at index 0.

Get the First Element of an Array in PowerShell

A PowerShell array is a data structure that stores a collection of items, which can be of the same type or different types. In PowerShell, arrays are incredibly flexible and can be easily manipulated.

To declare an array in PowerShell, you simply list the items separated by commas and assign them to a variable:

$myArray = "apple", "banana", "cherry"

In this example, $myArray is an array that contains three strings.

Accessing the First Element of a PowerShell array

Accessing the first element of an array in PowerShell is done by using the index 0. Arrays are zero-indexed, which means the first position is referred to as 0, the second as 1, and so on.

Here is the syntax to get the first element:

$myArray = "apple", "banana", "cherry"
$firstElement = $myArray[0]
Write-Output $firstElement

If we use the array from the previous example, $firstElement would contain the string "apple".

You can see the output in the screenshot below after I executed the script using VS code.

How to Get the First Element of an Array in PowerShell

Example: Retrieving the PowerShell Array First Element

Let’s look at a practical example. Suppose you have an array of service statuses obtained from the Get-Service cmdlet:

$services = Get-Service

To get the first service from this array, you would use the below PowerShell script:

$firstService = $services[0]

$firstService now holds the information about the first service returned by the Get-Service cmdlet.

Get the First Element of an Array in PowerShell – Another Example

In some cases, you might want to retrieve the first element and use it in a pipeline or another command without storing it in a variable. PowerShell allows you to do this in a streamlined way:

Get-Service | Select-Object -First 1

This command gets a list of services and pipes it into Select-Object, which selects the first item from the resulting array in PowerShell.

Conclusion

In this PowerShell tutorial, I have explained how to get the first element of an array in PowerShell using different methods.

You may also like: