質問

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