PowerShell: How to Return Longest String in an Array


Often you may want to find the longest string in an array in PowerShell.

You can use the following methods to do so:

Method 1: Return Longest String in Array

$my_array | Sort length -desc | Select -first 1

This particular example will return the longest string in the array named $my_array.

Method 2: Return Length of Longest String in Array

($my_array | Measure-Object -Maximum -Property Length).Maximum

This particular example will return the length of the longest string in the array named $my_array.

The following examples show how to use both methods in practice.

Example 1: Return Longest String in Array in PowerShell

Suppose that we create the following array in PowerShell named $my_array that contains the names of various basketball teams:

$my_array = @('Mavs', 'Celtics', 'Lakers', 'Grizzlies')

We can use the following syntax to return the longest string in the array:

$my_array | Sort length -desc | Select -first 1

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

PowerShell find longest string in array

This returns the string Grizzlies, which is indeed the longest string in the array.

Note: In this method we use the Sort command to first sort the strings based on length in descending order, then we use the Select command to select the first string from the sorted list, which represents the string with the longest length.

Example 2: Return Length of Longest String in Array in PowerShell

Once again, suppose that we create the following array in PowerShell named $my_array:

$my_array = @('Mavs', 'Celtics', 'Lakers', 'Grizzlies')

We can use the following syntax to return the length of the longest string in the array:

($my_array | Measure-Object -Maximum -Property Length).Maximum

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

This returns the value 9, which is the length of the longest string Grizzlies in the array.

Related Tutorials

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

PowerShell: How to Calculate the Average of an Array
PowerShell: How to Compare Two Arrays
PowerShell: How to Get First Item in Array
PowerShell: How to Find Duplicate Values in Array

Leave a Reply