使用 Measure-Object cmdlet 在数组中修剪 Powershell 前导零

Powershell Leading zeros are trimmed in array using Measure-Object cmdlet

当使用 Powershell 找出字符串数组中的最大值或最小值时,结果字符串的前导零会被删除。如何保留零?

$arr = @("0001", "0002", "0003")
($arr | Measure-Object -Maximum).Maximum
>>> 3 

枚举数组是最快的方法:

$max = ''
foreach ($el in $arr) {
    if ($el -gt $max) {
        $max = $el
    }
}
$max

或使用SortedSet from .NET 4 framework (built-in since Win 8),比Measure-Object快2倍,但比上面手动枚举慢2倍。如果您计划快速对不重复的数据进行排序,它仍然可能有用:它比 built-in Sort-Object.

更快
([Collections.Generic.SortedSet[string]]$arr).max

显然,它会为数组索引分配一些内存,但不会为实际数据分配一些内存,因为它会从现有数组中重复使用。如果您担心它,只需使用 [gc]::Collect()

强制垃圾回收

试试这个

$arr = @("0001", "0002", "0003")
$arr | sort -Descending | select -First 1