簡體   English   中英

使用PowerShell查找陣列中文件夾的大小

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

我有一個名為$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

}

您要遍歷$FolderArray兩次,一次是在foreach($i in $FolderArray)循環中,然后是在循環體內:

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

如果要單獨查看$FolderArray每個文件夾,請引用當前變量(在您的示例中為$i )。

我建議將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