Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 如何以最简单的方式获取当前目录中行数最多的五个文件?_Powershell - Fatal编程技术网

Powershell 如何以最简单的方式获取当前目录中行数最多的五个文件?

Powershell 如何以最简单的方式获取当前目录中行数最多的五个文件?,powershell,Powershell,在实用程序员的转换编程一章中有这样一个shell命令 它的功能是列出当前目录中行数最多的五个文件 $ find . -type f | xargs wc -l | sort -n | tail -6 | head -5 我正试图用PowerShell做同样的事情,但它似乎太罗嗦了 (Get-ChildItem .\ | ForEach-Object {$_ | Select-Object -Property 'Name', @{label = 'Lines'; expression = {($

在实用程序员的转换编程一章中有这样一个shell命令

它的功能是列出当前目录中行数最多的五个文件

$ find . -type f | xargs wc -l | sort -n | tail -6 | head -5
我正试图用PowerShell做同样的事情,但它似乎太罗嗦了

(Get-ChildItem .\ | ForEach-Object {$_ | Select-Object -Property 'Name', @{label = 'Lines'; expression = {($_ | Get-Content).Length}}} |Sort-Object -Property 'Lines')|Select-Object -Last 5
我相信会有一个更简单的方法,但我想不起来

如何使用PowerShell以最简单的方式获取当前目录中行数最多的文件


当然,您不需要使用自定义别名和缩写来缩短长度。虽然它看起来更简洁,但会失去可读性。

请尝试使用Linq的File.ReadLines或使用Count属性的File.ReadAllLines

File.ReadLines

获取子项。\-File| 选择对象-属性名称,@{n='Lines';e={ [System.Linq.Enumerable]::Count[System.IO.File]::ReadLines$\uq.FullName } }|排序对象-属性“行”-降序|选择对象-前5 File.ReadAllLines

Get-ChildItem .\ -File | 
    Select-Object -Property Name, @{n='Lines'; e= { 
            [System.IO.File]::ReadAllLines($_.FullName).Count 
        } 
    } | Sort-Object -Property 'Lines' -Descending | Select-Object -First 5

一种快速方法是使用开关文件:


我终于找到了自己满意的答案

使用3个管道操作器,外壳使用5个

更重要的是,我们得到的是对象,它可以用于更可扩展的操作

我感觉比linux的shell要好

dir -file | sort {($_ | gc).Length} | select -l 5

下面显示了获取文本文件行数的方法。。。PowerShell获取大文件的行数->>>堆栈溢出-有趣的是,我不知道get Content会将PSChildName等属性从其输入对象添加到其输出。文档中似乎缺少这一点。但请记住,与[System.IO.File]相比,性能确实很慢:阅读资料请参阅下面我的答案。尤其是在计算较大文件的行数时。在我的测试环境中:File.ReadLines=2.7秒,而Get Content=31.56秒seconds@pwnosh感谢您提醒我,当需要性能时,我们应该使用C,而不是cmdlet。但是,与Shell相比,“获取内容”的效率有多高?我很好奇,但我无法测试它,因为我根本不懂liunx。不完全是。您不需要C签名或编译的项目。在PowerShell Windows和Core中,您可以使用每个.NET Framework和Core类。NET是PowerShell、C、F等的底层框架。您可以直接在PowerShell中使用[System.IO.File]::Exists'C:\temp\test.log'。还是我误解了你的问题?@pwnosh谢谢你的补充。事实上,我明白这一点。这不容易描述,因此很容易引起误解。
$files = (Get-ChildItem -File ).FullName 
$result = foreach ($file in $files) {
    $lineCount = 0
    switch -File $file {
        default { $lineCount++ }
    }
    [PsCustomObject]@{
        File  = $file
        Lines = $lineCount
    }
}
$result | Sort-Object Lines | Select-Object -Last 5
Get-Content * | Group-Object PSChildName | Select-Object Count, Name |
    Sort-Object Count | Select-Object -Last 5
dir -file | sort {($_ | gc).Length} | select -l 5