Вопрос

I would like to get the longest string in an array, without looping through the whole array with foreach or do...until.

I tried this:

$Namelength = ($array | Measure-Object -Maximum).Maximum.ToString().Length

It seems to work with numbers. But not with strings (my strings contain "," "." "-" and "_")

I am somehow just getting some long strings, but not the longest - It is more like an average value.

Any idea to solve that?

Greetings and thanks in advance!

Это было полезно?

Решение

@Kayasax's answer will give you the string(value) for the longest string. The reason your code didn't work was because you measured the items in the array, not the length. For that, you need to specify the -Property Length parameter in Measure-Object, like this:

PS> ("lalala","hehe","hi" | Measure-Object -Maximum -Property Length).Maximum
6

Другие советы

$array1=@("test";"coucou","helloword")
$array1 | sort length -desc | select -first 1
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top