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