PowerShell: How to Get Last Item in Array


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

$my_array[-1]

This particular example will retrieve the last 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 Last 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 last file name in the array.

We can use the following syntax to do so:

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

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

PowerShell get last item in array

We can see that the name of the last file in the array is returned: players.csv.

If we would instead like to get the name of the second to last item in the array, then we could use the following syntax instead:

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

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

PowerShell get second to last item in array

We can see that the name of the second to last file in the array is returned: managers.csv.

Feel free to replace -2 with any value that you’d like to get the nth to last item in a given array.

Related Tutorials

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

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