【问题标题】:Efficiently finding an extremum有效地找到极值
【发布时间】:2014-03-09 23:37:31
【问题描述】:

commonanswer 到“我如何找到最新的文件”是:

dir | Sort-Object -Property LastWriteTime | Select-Object -Last 1

这对于大量文件来说效率不高。

有没有一种内置方法可以有效地找到极值?

【问题讨论】:

    标签: sorting powershell max


    【解决方案1】:

    还有更多的 .NET 程序员风格::-)

    [Linq.Enumerable]::First([Linq.Enumerable]::OrderByDescending((new-object IO.DirectoryInfo $pwd).EnumerateFiles(), [Func[IO.FileInfo,DateTime]]{param($f) $f.LastWriteTime}))
    

    这将返回完整的 .NET FileInfo 对象。它的执行顺序似乎与@mjolinor 的解决方案相同——在有限的测试中。

    【讨论】:

    • 不错! (虽然我认为我仍然是我的,如果我需要完整的对象,只需通过 Get-Item 运行结果)。
    • @mjolinor 您的解决方案肯定少了很多打字,而且更有可能被使用。 :-) 只是想在这里宣传使用 LINQ 作为一种有趣的替代方案。
    【解决方案2】:

    另一种方法:

    $newest = $null
    dir | % { if ($newest -eq $null -or $_.LastWriteTime -gt $newest.LastWriteTime) { $newest = $_ } }
    $newest
    

    【讨论】:

      【解决方案3】:

      对于大型目录,我所知道的最快的方法是:

      (cmd /c dir /b /a-d /tw /od)[-1]
      

      【讨论】:

        【解决方案4】:

        这是一种方法。函数Max

        function Max ($Property)
        {
            $max = $null
            foreach ($elt in $input)
            {
                if ($max -eq $null) { $max = $elt }
        
                if ($elt.$Property -gt $max.$Property) { $max = $elt }
            }
        
            $max
        }
        

        可用于定义Newest

        function Newest () { $input | Max LastWriteTime }
        

        可以这样调用:

        dir | Newest
        

        也可以用来定义Largest

        function Largest () { $input | Max Length }
        

        例如:

        dir -File | Largest
        

        同样,Min 可用于定义OldestSmallest

        function Min ($Property)
        {
            $min = $null
            foreach ($elt in $input)
            {
                if ($min -eq $null) { $min = $elt }
        
                if ($elt.$Property -lt $min.$Property) { $min = $elt }
            }
        
            $min
        }
        
        function Oldest () { $input | Min LastWriteTime }
        
        function Smallest () { $input | Min Length }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-05
          • 2014-12-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多