当只有 1 个文件匹配时,计算目录 returns 0 中的文件数?

Counting number of files in dir returns 0 when there is only 1 file match?

参考,我需要一个脚本来统计:

示例目录结构如下:

ROOT
    BAR001
        foo_1.txt
        foo_2.txt
        foo_ignore_this_1.txt
    BAR001_a
        foo_3.txt
        foo_4.txt
        foo_ignore_this_2.txt
        foo_ignore_this_3.txt
    BAR001_b
        foo_5.txt
        foo_ignore_this_4.txt
    BAR002
        baz_1.txt
        baz_ignore_this_1.txt
    BAR002_a
        baz_2.txt
        baz_ignore_this_2.txt
    BAR002_b
        baz_3.txt
        baz_4.txt
        baz_5.txt
        baz_ignore_this_3.txt
    BAR002_c
        baz_ignore_this_4.txt
    BAR003
        lor_1.txt

结构总是这样,所以没有更深的子文件夹。因为我只能使用 PS 2,所以我现在有:

Function Filecount {
    param
    (
        [string]$dir
    )

    Get-ChildItem -Path $dir | Where {$_.PSIsContainer} | Sort-Object -Property Name | ForEach-Object {
        $Properties = @{
            "Last Modified" = $_.LastWriteTime
            "Folder Name"   = $_.Name;
            Originals       = [int](Get-ChildItem -Recurse -Exclude "*_ignore_this_*" -Path $_.FullName).count
            Ignored    = [int](Get-ChildItem -Recurse -Include "*_ignore_this_*" -Path $_.FullName).count
        }
        New-Object PSObject -Property $Properties
    }
}

输出结果是这样的(Last Modified不填):

Folder Name      Last Modified    Originals    Ignored
-----------      -------------    ---------    -------
BAR001                                    2          1
BAR001_a                                  2          2
BAR001_b                                  0          0 <------- ??
BAR002                                    0          0 <------- ??
BAR002_a                                  0          0 <------- ??
BAR002_b                                  3          1

问题是只要目录中有 1 个文本文件和 1 个 "ignore" 文本文件,脚本就会为两列列出 0 而不是 1。我有不知道为什么。你呢?

您需要将 Get-ChildItem 中的 return 设为一个数组,这样即使它只有 returns 1,它也会有 .count 属性对象:

Function Filecount {
    param
    (
        [string]$dir
    )

    Get-ChildItem -Path $dir | Where {$_.PSIsContainer} | Sort-Object -Property Name | ForEach-Object {
        $Properties = @{
            "Last Modified" = $_.LastWriteTime
            "Folder Name"   = $_.Name;
            Originals       = @(Get-ChildItem -Recurse -Exclude "*_ignore_this_*" -Path $_.FullName).count
            Ignored         = @(Get-ChildItem -Recurse -Include "*_ignore_this_*" -Path $_.FullName).count
        }
        New-Object PSObject -Property $Properties
    }
}