Home ยป How to Get the Last Item in an Array Using PowerShell

How to Get the Last Item in an Array Using PowerShell

You can use multiple ways to get the last item in the array using PowerShell.

The following methods show how you can do it with syntax.

Method 1: Using index

$languages = @("PowerShell","Python","Java","C#")
$lastItem = $languages[-1]
Write-Output "Last item in the array is: $lastItem 

This example will output the last item in the array.

Method 2: Using the Select-Object cmdlet


$languages = @("PowerShell","Python","Java","C#")
$lastItem = $languages | Select-Object -Last 1
Write-Output "Last item in the array is: $lastItem"

This example will output the last item in the array using the Select-Object cmdlet.

The following examples show how you can use these methods.

Get the Last Item in the Array Using the Index in PowerShell

You can index in PowerShell to get the last element in an array.

# define an array
$languages = @("PowerShell","Python","Java","C#")

# use index to get last element of an array
$lastItem = $languages[-1]

# Write the output to the console
Write-Output "Last item in the array is: $lastItem 

Output:

Powershell get last item in array using index
Powershell get the last item in the array using the index

In this PowerShell script, the $languages variable is an array that stores the programming languages. We then use the index over the array variable like $languages[0] to get the last element of an array.

Finally, the last item in an array is output to the console using the Write-Output cmdlet.

Get the Last Item in an Array Using the Select-Object Cmdlet

You can use the Select-Object() method with its -Last 1 property to get the last item in an array.

# define an array
$languages = @("PowerShell","Python","Java","C#")

# use the Select-Object cmdlet to get last element of an array
$lastItem = $languages | Select-Object -Last 1

# Write the output to the console.
Write-Output "Last item in the array is: $lastItem"

Output:

Powershell get the last item in the array using Select-Object
Powershell get the last item in the array using Select-Object

In this script, the $languages variable is an array that stores the programming languages. We then use the Select-Object cmdlet with the -Last 1 parameter to get the last item in an array.

Finally, the last item in an array is output to the console using the Write-Output cmdlet.

Conclusion

I hope the above article on getting the last item in an array in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.