我有一个名为$FolderArray
的文件夹数组。它包含大约40个文件夹。每个文件夹里面都有一堆txt
个文件。我想遍历每个文件夹以获取每个文件夹中的文件数,以及每个文件夹的总大小。我得到了每个文件夹中的文件数量,但是对于文件夹大小,它最终会输出每个文件夹中最后一个文件的文件大小。
我从我的代码片段中删除了这个,所以如果需要更多说明,请告诉我。我很感激帮助!
$ProcessedLocation = "C:\Users\User.Name\Documents"
$FolderArray = gci -Path $ProcessedLocation | Where-Object {$_.PSIsContainer} | Foreach-Object {$_.Name}
Foreach ($i in $FolderArray)
{
$FolderLocation = $ProcessedLocation + $i
[int]$FilesInFolder = 0
Get-ChildItem -Path $FolderLocation -Recurse -Include '*.txt' | % {
$FilesInFolder = $FilesInFolder + 1
$Length = $_.Length
$FolderSize = $FolderSize + $Length
}
Write-Host $FolderSize
}
答案 0 :(得分:2)
您在$FolderArray
循环中迭代foreach($i in $FolderArray)
两次,然后再循环到循环体内:
foreach($i in $FolderArray){
Get-ChildItem $FolderArray # don't do this
}
如果您想单独查看$FolderArray
中的每个文件夹,请引用当前变量(在您的示例中为$i
)。
我建议将Get-ChildItem
的输出保存到变量中,然后从中获取文件的大小和数量:
# keep folders as DirectoryInfo objects rather than strings
$FolderArray = Get-ChildItem -Path $ProcessedLocation
foreach ($Folder in $FolderArray)
{
# retrieve all *.txt files in $Folder
$TxtFiles = Get-ChildItem -Path $Folder -Recurse -Include '*.txt'
# get the file count
$FilesInFolder = $TxtFiles.Count
# calculate folder size
$FolderSize = ($TxtFiles | Measure -Sum Length).Sum
# write folder size to host
$FolderSizeMB = $FolderSize / 1MB
Write-Host "$Folder is $FolderSizeMB MB in size"
}