Pr0no
Pr0no

Reputation: 4099

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

Referring to my previous post, I am in need of a script to count the number of:

The example directory structure would be like this:

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

The structure will always be like this, so no deeper subfolders. Because I am restricted to using PS 2, I now have:

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

The output is like this (Last Modified not filled in):

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

The problem is that the whenever there is 1 textfile and 1 "ignore" textfile in a directory, the script lists 0 for both columns instead of 1. I have no clue why. Do you?

Upvotes: 1

Views: 481

Answers (1)

mjolinor
mjolinor

Reputation: 68273

You need to make the return from Get-ChildItem an array, so that it will have .count property even if it only returns 1 object:

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

Upvotes: 2

Related Questions