Reputation: 13
I am creating a script that sums up the sizes of every file under directory red line by line from a file.
Right now the recursive search for files is working and I get a sum for sizes for each line of the source file but I am not sure on how to add all those values together.
What I have right now is:
#Read each line of a file for a directory
foreach($line in Get-Content .\file.txt) {
#Prints the current line path
echo $line
#Prints a count of the files under that path and a sum of all files length
Get-ChildItem -Recurse $line | Measure-Object -Property Length -Sum
}
The output of this scripts looks like:
T:/folder_1/folder_2/2018/12/6/A
Count : 30
Average :
Sum : 522382636
Maximum :
Minimum :
Property : Length
T:/folder_1/folder_2/2018/12/6/B
Count : 2
Average :
Sum : 2835134
Maximum :
Minimum :
Property : Length
How can I get the sum of every Sum output for every folder, i.e., the sum of all .Sum
property values?
Upvotes: 1
Views: 695
Reputation: 440102
Combining the suggestions by notjustme and Ansgar Wiechers:
Get-Content .\file.txt | ForEach-Object -ov results {
# Calculate the total size for the path at hand, and
# output the result as a custom object.
[pscustomobject] @ {
Path = $_
Length = (Get-ChildItem -Recurse $_ | Measure-Object -Property Length -Sum).Sum
}
} | Measure-Object -Property Length -Sum | Select-Object -ExpandProperty Sum
# Use $results to access the per-path values.
Note how an outer Measure-Object
is used to sum the results of the per-path Measure-Object
results.
If you don't need to store the per-path results and just want the overall sum, the solution becomes much simpler, as Ansgar observes:
(Get-ChildItem -LiteralPath (Get-Content .\file.txt) -Recurse |
Measure-Object -Property Length -Sum).Sum
Note how the array of lines output by Get-Content
is directly passed to -LiteralPath
, which is supported, because both -Path
and -LiteralPath
are defined as [string[]]
(string arrays).
Upvotes: 3