简体   繁体   English

使用PowerShell查找阵列中文件夹的大小

[英]Find size of folders in an array using PowerShell

I have an array of folders, called $FolderArray . 我有一个名为$FolderArray的文件夹数组。 It contains about 40 folders. 它包含大约40个文件夹。 Inside each folder are a bunch of txt files. 每个文件夹中都有一堆txt文件。 I want to loop through each folder to get the number of files in each folder, as well as the total size of each folder. 我想遍历每个文件夹以获取每个文件夹中的文件数以及每个文件夹的总大小。 I got the number of files in each folder to work, but for the folder size, it ends up outputting the file size of the last file in each folder. 我得到了每个文件夹中可工作的文件数,但是对于文件夹大小,最终输出每个文件夹中最后一个文件的文件大小。

I pulled this out of a larger snippet of my code, so if anything needs more clarification please let me know. 我从代码的较大片段中删除了此代码,因此如果需要进一步说明,请告诉我。 I appreciate the help! 感谢您的帮助!

$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

}

You are iterating over $FolderArray twice, once in the foreach($i in $FolderArray) loop, and then again inside the loop body: 您要遍历$FolderArray两次,一次是在foreach($i in $FolderArray)循环中,然后是在循环体内:

foreach($i in $FolderArray){
    Get-ChildItem $FolderArray # don't do this
}

If you want to look into each folder in $FolderArray individually, reference the current variable (in your example that would be $i ). 如果要单独查看$FolderArray每个文件夹,请引用当前变量(在您的示例中为$i )。

I would recommend saving the output from Get-ChildItem to a variable and then grab the size and count of the files from that: 我建议将Get-ChildItem的输出保存到变量,然后从中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"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM