简体   繁体   中英

PowerShell: Count files in a given name directory and subfolders

I need to count files inside given folders

example:

Folder A
Folder B
Folder C

For each folder I need to count how many files there are, and at the end sum the total.

What is the best to way to do this?

try this:

$DirList=@('C:\temp\BATCHHISTOCRE', 'C:\temp\tmp', 'C:\temp\444')

$DirList | %{

    [pscustomobject]@{
    Dirname=$_
    NbFile=(Get-ChildItem -Path $_ -File).Count # Add -recurse if you want all tree into your dir
     }
}

在此处输入图像描述

Tagging on to @Esperento57: , helpful answer.

Yeppers, it does work, but it will also error off if the folder path has no files; whereas using Measure-Object in the mix, can address that.

$DirList = @('D:\Temp\AddressFiles',
'D:\Temp\BonoboGitServer',
'D:\Temp\Book'
)

$DirList | 
ForEach-Object {
    [pscustomobject]@{
        Dirname = $PSItem
        NbFile  = (Get-ChildItem -Path $PSItem -File).Count
    }
}
# Results
<#
Dirname              NbFile
-------              ------
D:\Temp\AddressFiles      3
The property 'Count' cannot be found on this object. Verify that the property exists.
At line:8 char:5
+     [pscustomobject]@{
+     ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

D:\Temp\Book              4
#>

Whereas using the Measure-Object cmdlet, addresses the issue...

$DirList = @('D:\Temp\AddressFiles',
'D:\Temp\BonoboGitServer',
'D:\Temp\Book'
)

$DirList | 
ForEach-Object {
    [pscustomobject]@{
        Dirname = $PSItem
        NbFile  = (Get-ChildItem -Path $PSItem -File | 
                  Measure-Object).Count
    }
}
# Results
<#

Dirname                 NbFile
-------                 ------
D:\Temp\AddressFiles         3
D:\Temp\BonoboGitServer      0
D:\Temp\Book                 4
#>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM