Memory 使用Powershell检查许多文件夹

Memory 使用Powershell检查许多文件夹,memory,powershell,foreach,internal,subdirectory,Memory,Powershell,Foreach,Internal,Subdirectory,我的问题是Powershell。 我有一个很大的文件夹。Insider大约有160万个子文件夹。 我的任务是清除所有的空文件夹或文件下,这是超过6个月。 我用foreach编写了一个循环,但powershell需要很长时间才能开始使用它-> 问题是:我的内存已满(4GB),无法正常工作。 我的猜测是:powershell加载了所有160 000个文件夹,然后才开始过滤它们 是否有可能防止这种情况发生?没错,所有160万个文件夹或至少对它们的引用都将立即加载。最佳实践是左过滤右格式化;注意,如

我的问题是Powershell。 我有一个很大的文件夹。Insider大约有160万个子文件夹。 我的任务是清除所有的空文件夹或文件下,这是超过6个月。 我用foreach编写了一个循环,但powershell需要很长时间才能开始使用它->

问题是:我的内存已满(4GB),无法正常工作。 我的猜测是:powershell加载了所有160 000个文件夹,然后才开始过滤它们


是否有可能防止这种情况发生?

没错,所有160万个文件夹或至少对它们的引用都将立即加载。最佳实践是左过滤右格式化;注意,如果可能的话,在点击
Where Object
之前删除这些文件夹(不幸的是,
gci
不支持日期过滤器AFAICT)。而且,如果你把东西放在管道中,你会使用更少的内存

以下内容将限制
$items
仅限于符合条件的文件夹,然后在这些对象上执行循环

$items = Get-ChildItem -path $rootpath -recurse -force | ?{ $_.LastWriteTime -lt $date }
foreach ($item in $items) {
# here comes a script which will erase the file when its older than 6 months
# here comes a script which will erase the folder if it's a folder AND does not have child items of its own
}
或进一步精简:

function runScripts {
    # here comes a script which will erase the file when its older than 6 months. Pass $input into that script. $input will be a folder.
    # here comes a script which will erase the folder if it's a folder AND does not have child items of its own Pass $input into that script. $input will be a folder.
}
Get-ChildItem -path $rootpath -recurse -force | ?{ $_.LastWriteTime -lt $date }|runScripts

在最后一个例子中,您使用的是
runScripts
函数,它使用管道对象作为可以操作的参数(
$input
),因此您可以通过管道发送所有内容,而不是使用那些中间对象(这将消耗更多内存)。

谢谢,我刚刚在较小的环境中测试了它。(106000个文件夹)我的原稿花了大约73秒。有了你的修改(精简),我只花了51秒。谢谢
function runScripts {
    # here comes a script which will erase the file when its older than 6 months. Pass $input into that script. $input will be a folder.
    # here comes a script which will erase the folder if it's a folder AND does not have child items of its own Pass $input into that script. $input will be a folder.
}
Get-ChildItem -path $rootpath -recurse -force | ?{ $_.LastWriteTime -lt $date }|runScripts