巨大目录和 RAM 使用中的 Get-ChildItem

Get-ChildItem in an enormous directory and RAM usage

我在域控制器 (SRV2012R2) 上创建了一个 PS 脚本。

脚本检查每个共享文件夹(映射驱动器)以查看是否存在任何大于 2GB 的文件:

foreach($dir in $Dirs)
{
    $files = Get-ChildItem $dir -Recurse 

    foreach ($item in $files)
    {

       #Check if $item.Size is greater than 2GB

    }
}

我有以下问题:

共享中充满了超过 800GB 的(子)文件夹、文件,其中大部分只是普通文档。

每当我 运行 我的脚本时,我都会看到 CPU+RAM 在 运行 运行我的脚本时消耗了大量内存(进入 Get-Childitem- 5 分钟后线,RAM 已经达到 >4GB)。

我的问题是,为什么 Get-ChildItem 需要这么多资源?我可以使用什么替代方案?因为我还没有成功 运行 我的脚本。

我发现我可以在 Get-ChildItem 子句之后使用 | SELECT fullname, length 作为改进,但这对我没有任何帮助(查询仍然消耗大量 RAM)。

有什么我可以做的,以便我可以在没有太多机器资源阻力的情况下循环访问目录?

不是将每个文件都保存到变量中,而是使用管道过滤掉不需要的文件(即小于 2GB 的文件):

foreach($dir in $Dirs)
{
    $bigFiles = Get-ChildItem $dir -Recurse |Where Length -gt 2GB
}

如果您需要进一步处理或分析这些大文件,我建议您使用 ForEach-Object:

扩展该管道
foreach($dir in $Dirs)
{
    Get-ChildItem $dir -Recurse |Where Length -gt 2GB |ForEach-Object {
      # do whatever else you must
      # $_ contains the current file
    }
}

试试这个:

# Create an Array
$BigFilesArray = @()

#Populate it with your data
$BigFilesArray = @(ForEach-Object($dir in $dirs) {Get-ChildItem $dir -Recurse | Where-Object Length -GT 2GB})

#Number of items in the array
$BigFilesArray.Count

#Looping to get the name and size of each item in the array
ForEach-Object ($bf in $BigFilesArray) {"$($bf.name) - $($bf.length)"}

希望对您有所帮助!