powershell 使用聚合计算路径数

bgtovc5b  于 2022-11-10  发布在  Shell
关注(0)|答案(2)|浏览(302)

我有几个文件,其中包含共享驱动器上文件的完整路径列表。例如:

\\server\share$\Public\HR\reports\report.doc
\\server\share$\Public\HR\reports\report.xls

我正在尝试获取每个目录的文件数,其中聚合位于顶部:

\\server\share$\Public:200
\\server\share$\Public\HR: 10
\\server\share$\Public\HR\reports: 2

到目前为止,我有:

foreach ($file in Get-ChildItem C:\scripts\FMU)
{
    foreach ($path in Get-Content $file)
    {
        while ($path -ne "")
        {
            $path = $path | Split-Path
            $array.$path.value, count++ #Not sure how to increment the count of the path value in the array
        }
    }
}

如何设置一个数组来计算所有路径?
谢谢,

ryevplcw

ryevplcw1#

您可以使用Group-Object获取每条路径的计数:

$paths = foreach ($file in (Get-ChildItem C:\scripts\FMU)) {
  foreach ($path in Get-Content $file){
    $path | Split-Path
  }
}

$grouped = $paths | Group-Object | select Count,Name

# outputs like:

Count Name                                                                                                
----- ----                                                                                                
   10 C:\folder1                                                                                
  200 C:\folder1\folder2\folder3                                                                
    3 C:\folder1\folder4

编辑:添加了作为第二步执行完全聚合的功能。


# aggregate file counts as a second step

$aggregates = Foreach ($group in ($grouped|sort Name)) {

  # get sub-folders
  $children = $grouped | where { $_.Name -like ($group.Name+'\*') }

  # aggregate counts
  # count property can't be used because of count method name collision
  $group.Count = ($children|% count|measure -Sum).Sum + $group.count
  $group
}

$aggregates
jbose2ul

jbose2ul2#

感谢您提出组对象的想法。以下是奏效的方法。

foreach ($file in Get-ChildItem C:\scripts\FMU)
{
    foreach ($path in Get-Content $file)
    {
        while ($path -ne "")
        {
            $path = $path | Split-Path
            $path
        }
    }
}
$paths | Group-Object | Select-Object Count, Name

花了一段时间,但还是奏效了。
可以对其进行修改,以取代以下内容

foreach ($item in Get-ChildItem -Recurse) {Get-ChildItem -Recurse -File).Count}

谢谢

相关问题