我想创建一个脚本,将 3 个文件的大小输出到一个文本文件。并且大小将以 GB 为单位显示。我该如何实现这个功能?
答案1
使用获取项目和导出-Csvcmdlet 中你可以使用类似这样的命令:
# files to check for size
$files = @(
"C:\Users\JohnDoe\file1.txt",
"C:\Users\JohnDoe\file2.txt",
"C:\Users\JohnDoe\file3.txt"
)
# path where results will be written
$export = "C:\Users\JohnDoe\list.txt"
foreach ($file in $files) {
# create suiting object
$output = "" | select "SizeGB", "Name"
# get item information
$item = Get-Item -Path $file
# transfer size to GB with 2 decimals and write into object
$output.SizeGB = [math]::round($item.Length/1GB,2)
# write name into object
$output.Name = $item.Name
#export into csv
$output | Export-csv $export -Append -NoTypeInformation
}
输出将采用 csv 样式,如下所示:
"SizeGB","Name"
"0.06","file1.txt"
"0.09","file2.txt"
"0.04","file3.txt"