当只有1个文件匹配时,在dir中计算文件数会返回0吗?

时间:2015-02-06 11:57:53

标签: powershell

参考my previous post,我需要一个脚本来计算数字:

  • 常规文本文件
  • 名称中包含特定字符串的文本文件

示例目录结构如下:

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
    }
}

输出如下(上次修改未填写):

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个“忽略”文本文件时,脚本会为两列而不是1列出0.我不知道为什么。你呢?

1 个答案:

答案 0 :(得分:2)

您需要从Get-ChildItem数组返回,以便它具有.count属性,即使它只返回1个对象:

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
    }
}