I'm very new to powershell. I have a txt file with a subset of UNC paths to directories that i need to determine the size of each of them. I've come up with the following which is working as intended but i have a couple of problems.
FUNCTION FileSize
{$DB = Get-Content 'C:\path\path\path\path\paths2.txt'
foreach ($Data in $DB)
{"{0:N2} GB" -f ((Get-ChildItem "$Data" -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1GB)}}
I need to add into this the ability to see the UNC path that the size reading belongs too and fi could also output the results to a txt file that would beneficial too. All attempts so far have been futile.
Thanks, Allan
BenH's helpful answer provides an effective solution that performs the output formatting directly inside the FileSize
function.
Alternatively, for more flexibility, consider refactoring your approach so as to separate the aspects of data gathering and output formatting :
First, modify your function:
.Path
property containing the file path at hand, .Size
property containing the aggregate size as a number (type [double]
. Function FileSize {
param(
[string] $PathsFile
)
foreach ($path in Get-Content $PathsFile) {
[pscustomobject] @{
Path = $path
Size = (Get-ChildItem -File $path -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum
}
}
}
The data-only output of the function then lets you decide later how to format the data and where to save it:
Using BenH's approach in a ForEach-Object
call:
FileSize 'C:\path\path\path\path\paths2.txt' |
ForEach-Object { '{0} : {1:N2} GB' -f $_.Path, ($_.Size/1GB) }
You can simply append > out.txt
, for instance, to save the output in a file; alternatively, piping to Out-File
or Set-Content
allows you to control the output file's character encoding with the -Encoding
parameter.
To produce friendly tabular output for display , you can pipe to Format-Table
using a calculated property :
FileSize 'C:\path\path\path\path\paths2.txt' |
Format-Table Path, @{ n='Size'; e={ '{0:N2} GB' -f ($_.Size/1GB) } }
Finally, for further programmatic processing, you can pipe FileSize
output to export cmdlets such as Export-Csv
and Export-CliXml
or even conversion cmdlets such as ConvertTo-Json
.
It appears that you have the UNC path information stored in $Data
, so you could add it in front of your output string. The save the output of the whole loop in a variable and you can export it by piping to Out-File
, Add-Content
, or Set-Content
.
function FileSize {
$DB = Get-Content 'C:\path\path\path\path\paths2.txt'
$Sizes = foreach ($Data in $DB) {
"$Data : {0:N2} GB" -f ((Get-ChildItem "$Data" -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1GB)
}
$Sizes | Out-File 'C:\path\path\path\path\out.txt'
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.