PowerShell: How to Get First Item in Array


You can use the following syntax in PowerShell to get the first item in an array:

$my_array[0]

This particular example will retrieve the first item in the array named $my_array.

Note: This method is known as subscripting an array. More documentation on subscripting can be found here.

The following example shows how to use this syntax in practice.

Example: How to Get First Item in Array in PowerShell

Suppose that our current directory has the following path:

  • c:\users\bobbi\data4

We can type Dir to list out all files in this current directory:

We can see that there are five files in this directory.

Suppose that we we would like to create an array that contains each of the file names in this directory and then access the first file name in the array.

We can use the following syntax to do so:

$my_files = Get-ChildItem $source -Name
$my_files[0]

The following screenshot shows how to use this syntax in practice:

PowerShell get first item in array

We can see that the name of the first file in the array is returned: basketball_data.csv.

If we would instead like to get the name of the first three items in the array, then we could use the following syntax:

$my_files = Get-ChildItem $source -Name
$my_files[0..2]

The following screenshot shows how to use this syntax in practice:

PowerShell get first n items in array

We can see that the name of the first three files are returned:

  • basketball_data.csv
  • basketball_data2.csv
  • coaches.csv

Note that the syntax $my_files[0..2] tells PowerShell to retrieve all items in index positions between 0 and 2 in the array, which represent the first three items in the array.

To retrieve a different number of items from the start of the array, simply change the 2 to a different number.

For example, if you want the first 5 items in the array then use $my_files[0..4] instead.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Get Last Item in Array
PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Get List of Files Modified After Certain Date

Leave a Reply