【问题标题】:List file count by subfolder按子文件夹列出文件数
【发布时间】:2018-11-30 18:40:31
【问题描述】:

我正在尝试使用 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\1\2\-movi...)。有没有办法只显示最后一个文件夹(“电影”)并将结果保存到 .txt 文件?

谢谢

【问题讨论】:

    标签: powershell subdirectory


    【解决方案1】:

    而不是$_.FullName,使用$_.Name 仅获取目录名称

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

    虽然使用> 将结果发送到.txt 文件很容易,但最好使用更结构化的格式以供以后程序化 处理。 在最简单的形式中,这意味着通过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 调用替换为使用calculated propertySelect-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
    

    【讨论】:

    • 我很高兴,@MikeP。请参阅我的更新,了解如何简化命令。通常,使用Get-Member cmdlet 来检查命令的输出类型,这样您就可以发现完整的类型名称和可用的属性/方法。
    【解决方案2】:

    你的意思是这样的......

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

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2011-05-11
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多