I have a few files with list of full paths to files on the share drive. For example:
\\server\share$\Public\HR\reports\report.doc
\\server\share$\Public\HR\reports\report.xls
I am trying to get a count of files per directory with aggregates to the top:
\\server\share$\Public:200
\\server\share$\Public\HR: 10
\\server\share$\Public\HR\reports: 2
So far I have:
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
}
}
}
How do I set up an array to count all of the paths?
Thanks,
CodePudding user response:
You can use Group-Object
to get a count of of each path:
$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
Edit: added doing a full aggregate as a second step.
# 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
CodePudding user response:
Thank you for the Group-Object idea. Here is what worked.
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
Took a while, but it worked.
This could be modified to replace something like
foreach ($item in Get-ChildItem -Recurse) {Get-ChildItem -Recurse -File).Count}
Thanks