Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 使用PowerShell查找阵列中文件夹的大小_Arrays_Powershell - Fatal编程技术网

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

Arrays 使用PowerShell查找阵列中文件夹的大小,arrays,powershell,Arrays,Powershell,我有一个文件夹数组,名为$FolderArray。它包含大约40个文件夹。每个文件夹中都有一堆txt文件。我想循环遍历每个文件夹,以获得每个文件夹中的文件数以及每个文件夹的总大小。我得到了每个文件夹中要工作的文件数,但对于文件夹大小,它最终输出每个文件夹中最后一个文件的文件大小 我从我的一个更大的代码片段中提取了这个,所以如果需要更多的澄清,请让我知道。我感谢你的帮助 $ProcessedLocation = "C:\Users\User.Name\Documents" $FolderArray

我有一个文件夹数组,名为
$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($FolderArray中的i)
循环中,然后在循环体中再次迭代:

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"
}

您可以在
$FolderArray
上循环两次。
$FolderArray
是字符串或对象的数组吗(可能会先告诉我们您是如何填充/分配的)?@MathiasR.Jessen我编辑了它以提供更多的上下文。