使用PowerShell递归查找文件扩展名计数

时间:2017-12-11 13:40:51

标签: powershell

希望获得一个PowerShell代码段,该代码段将在文件夹中递归列出所有文件扩展名以及计数。

/abc/(1).cfc
/abc/john/(265).cfm, (1).html
/abc/john/js/(25).js
/abc/john/css/(6).css

这是我到目前为止所尝试的,但我不确定如何为每个添加路径:

Get-Childitem "C:\projects\newfolder\edit" -Recurse |
    where { -not $_.PSIsContainer } |
    group Extension -NoElement |
    sort count -Desc

3 个答案:

答案 0 :(得分:1)

您可以按多个条件进行分组:

Get-ChildItem 'C:\projects\newfolder\edit' -Recurse |
    Where-Object { -not $_.PSIsContainer } |
    Group-Object DirectoryName, Extension

在PowerShell v3及更新版本上,可以使用Get-ChildItem直接进行过滤:

Get-ChildItem 'C:\projects\newfolder\edit' -Recurse -File |
    Group-Object DirectoryName, Extension

答案 1 :(得分:1)

@AnsgarWiechers发布的答案是好的,如果你想要匹配文件的列表以及计数;如果你只想要目录名和计数,

(Powershell v2 :)

Get-ChildItem 'C:\projects\newfolder\edit' -Recurse |
    Where-Object { -not $_.PSIsContainer } |
    Group-Object DirectoryName, Extension |
    Select-Object Name, Count

(PowerShell v3 +:)

Get-ChildItem 'C:\projects\newfolder\edit' -Recurse -File |
    Group-Object DirectoryName, Extension |
    Select-Object Name, Count

答案 2 :(得分:0)

您可以使用以下脚本来实现预期的输出:

Get-ChildItem "C:\TempFiles" -Recurse -File | Group-Object DirectoryName |
ForEach-Object { 
    "{0}\{1}" -f $_.Name,
     (($_.Group | Group-Object Extension | 
        ForEach-Object { ("({0}){1}" -f $_.Count, $_.Name) }) -join ",")
} 

输出

C:\TempFiles\Root\(1).json,(2).html,(2).txt
C:\TempFiles\Root\Folder1\(4).json,(2).html,(2).txt,(2).png
C:\TempFiles\Root\Folder1\Folder1-1\(2).json,(2).html
C:\TempFiles\Root\Folder2\(2).txt