递归计算子文件夹中的文件 [英] Recursively count files in subfolders

查看:43
本文介绍了递归计算子文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算目录中所有子文件夹中的文件并将它们显示在列表中.

I am trying to count the files in all subfolders in a directory and display them in a list.

例如以下目录树:

TEST
    /VOL01
        file.txt
        file.pic
    /VOL02
        /VOL0201
            file.nu
            /VOL020101
                file.jpg
                file.erp
                file.gif
    /VOL03
        /VOL0301
            file.org

应该作为输出:

PS> DirX C:\TEST

Directory              Count
----------------------------
VOL01                      2
VOL02                      0
VOL02/VOL0201              1
VOL02/VOL0201/VOL020101    3
VOL03                      0
VOL03/VOL0301              1

我从以下几点开始:

Function DirX($directory)
{
    foreach ($file in Get-ChildItem $directory -Recurse)
    {
        Write-Host $file
    }
}

现在我有一个问题:为什么我的函数没有递归?

Now I have a question: why is my Function not recursing?

推荐答案

这样的事情应该可行:

dir -recurse |  ?{ $_.PSIsContainer } | %{ Write-Host $_.FullName (dir $_.FullName | Measure-Object).Count }

  • dir -recurse 列出当前目录下的所有文件并用管道 (|) 将结果传送到
  • ?{ $_.PSIsContainer } 过滤目录,然后再次通过管道将结果列表传送到
  • %{ Write-Host $_.FullName (dir $_.FullName | Measure-Object).Count } 这是一个 foreach 循环,对于列表的每个成员 ($_)显示以下表达式的全名和结果
  • (dir $_.FullName | Measure-Object).Count 提供 $_.FullName 路径下的文件列表,并通过 测量对象

    • dir -recurse lists all files under current directory and pipes (|) the result to
    • ?{ $_.PSIsContainer } which filters directories only then pipes again the resulting list to
    • %{ Write-Host $_.FullName (dir $_.FullName | Measure-Object).Count } which is a foreach loop that, for each member of the list ($_) displays the full name and the result of the following expression
    • (dir $_.FullName | Measure-Object).Count which provides a list of files under the $_.FullName path and counts members through Measure-Object

      ?{ ... } 是 Where-Object

      ?{ ... } is an alias for Where-Object

      这篇关于递归计算子文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆