【问题标题】:check A LOT of folders with Powershell使用 Powershell 检查很多文件夹
【发布时间】:2012-09-10 14:00:00
【问题描述】:

我的问题在于 Powershell。 我有一个很大的文件夹。 Insider 大约有 1 600 000 个子文件夹。 我的任务是删除它们下面所有超过 6 个月的空文件夹或文件。 我用 foreach 写了一个循环,但是在 powershell 开始之前需要很长时间 ->

...

foreach ($item in Get-ChildItem -Path $rootPath -recurse -force | Where-Object -FilterScript { $_.LastWriteTime -lt $date })
{
# 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

...

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

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

【问题讨论】:

    标签: memory powershell foreach internal subdirectory


    【解决方案1】:

    你是对的,所有 160 万个文件夹,或者至少是对它们的引用,都是一次加载的。最佳做法是向左过滤并向右格式化; IOW,如果可能的话,在你点击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),因此您可以通过管道发送所有内容,而不是使用那些中间对象(这将消耗更多内存)。

    【讨论】:

    • 谢谢,我刚刚在一个较小的环境中进行了测试。 (106 000 个文件夹)我的原始脚本花了大约 73 秒。有了你的修改(精简),我只花了 51 秒。谢谢!
    猜你喜欢
    • 2012-05-11
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    相关资源
    最近更新 更多