按子文件夹列出文件数

List file count by subfolder

我正在尝试使用 powershell 生成文件夹名称列表以及每个文件夹中有多少文件。

我有这个脚本

$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

其中列出了文件数,但它提供了完整路径(即 C:\Users\name\Desktop\-movi...)。有没有办法只显示最后一个文件夹 ("movies") 并将结果保存到 .txt 文件?

谢谢

你的意思是这样的...

Clear-Host
Get-ChildItem -Path 'd:\temp' -Recurse -Directory | 
Select-Object Name,FullName,
@{Name='FileCount';Expression = {(Get-ChildItem -Path $_.FullName -File -Recurse| Measure-Object).Count}} `
| Format-Table -AutoSize

# Results


Name           FullName                               FileCount
----           --------                               ---------
abcpath0       D:\temp\abcpath0                               5
abcpath1       D:\temp\abcpath1                               5
abcpath2       D:\temp\abcpath2                               5
Duplicates     D:\temp\Duplicates                         12677
EmptyFolder    D:\temp\EmptyFolder                            0
NewFiles       D:\temp\NewFiles                               4
PngFiles       D:\temp\PngFiles                               4
results        D:\temp\results                              905
...

而不是 $_.FullName,使用 $_.Name 只获取目录 name.

您的 Select-Object 调用是多余的 - 它实际上是空操作。

虽然使用 > 很容易将结果发送到 .txt 文件,但最好为以后的 programmatic[=35= 使用更结构化的格式] 加工。 在最简单的形式中,这意味着通过 Export-Csv 输出到 CSV 文件;然而,一般来说,将对象序列化到文件的最可靠方法是使用 Export-CliXml.

使用Export-Csv进行序列化:

$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

请注意,您可以通过将 ForEach-Object 调用替换为使用 :

Select-Object 调用来简化命令
$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