Search code examples
powershellsubdirectory

List file count by subfolder


I am trying to use powershell to produce a list of folder names and how many files are in each folder.

I have this script

$dir = "C:\Users\folder" 
Get-ChildItem $dir -Recurse -Directory | ForEach-Object{
    [pscustomobject]@{
        Folder = $_.FullName
        Count = @(Get-ChildItem -Path $_.Fullname -File).Count
    }
} | Select-Object Folder,Count

Which lists the file count, but it puts the full path (i.e. C:\Users\name\Desktop\1\2\-movi...). Is there any way to just display the last folder ("movies") as well as save the result to a .txt file?

Thank you


Solution

  • Instead of $_.FullName, use $_.Name to only get the directory name.

    Your Select-Object call is redundant - it is effectively a no-op.

    While it's easy to send the results to a .txt file with >, for instance, it's better to use a more structured format for later programmatic processing. In the simplest form, that means outputting to a CSV file via Export-Csv; generally, however, the most faithful way of serializing objects to a file is to use Export-CliXml.

    Using Export-Csv for serialization:

    $dir = 'C:\Users\folder'
    Get-ChildItem -LiteralPath $dir -Recurse -Directory | ForEach-Object {
        [pscustomobject] @{
          Folder = $_.Name
          Count = @(Get-ChildItem -LiteralPath $_.Fullname -File).Count
        }
    } | Export-Csv -NoTypeInformation results.csv
    

    Note that you could streamline your command by replacing the ForEach-Object call with a Select-Object call that uses a calculated property:

    $dir = 'C:\Users\folder'
    Get-ChildItem -LiteralPath $dir -Recurse -Directory |
      Select-Object Name,
        @{ n='Count'; e={@(Get-ChildItem -LiteralPath $_.Fullname -File).Count} } |
          Export-Csv -NoTypeInformation results.csv