【问题标题】:Powershell get-childitem needs a lot of memoryPowershell get-childitem 需要大量内存
【发布时间】:2015-03-13 17:27:04
【问题描述】:

我的问题与 metafilter 上发布的问题几乎相同。

我需要使用 PowerShell 脚本来扫描大量文件。问题是“Get-ChildItem”功能似乎坚持将整个文件夹和文件结构推入内存。由于驱动器在 30,000 多个文件夹中有超过 100 万个文件,因此该脚本需要大量内存。

http://ask.metafilter.com/134940/PowerShell-recursive-processing-of-all-files-and-folders-without-OutOfMemory-exception

我只需要文件的名称、大小和位置。

从现在开始我要做的是:

$filesToIndex = Get-ChildItem -Path $path -Recurse | Where-Object { !$_.PSIsContainer }

它有效,但我不想惩罚我的记忆:-)

最好的问候, 菜鸟

【问题讨论】:

    标签: powershell directory


    【解决方案1】:

    如果您想优化脚本以使用更少的内存,则需要正确利用管道。您正在做的是将 Get-ChildItem -recurse 的结果保存到内存中,全部!你可以做的是这样的:

    Get-ChildItem -Path $Path -Recurse | Foreach-Object {
        if (-not($_.PSIsContainer)) {
            # do stuff / get info you need here
        }
    }
    

    这样,您始终可以通过管道流式传输数据,并且您会发现 PowerShell 将消耗更少的内存(如果操作正确)。

    【讨论】:

    • 谢谢,非常感谢您的回答。我是 Powershell 的新手,并不真正知道如何使用管道。但这似乎是一件非常好的事情:-)
    【解决方案2】:

    您可以做的一件事是减少您保存的对象的大小,方法是将它们缩减为您感兴趣的属性。

    $filesToIndex = Get-ChildItem -Path $path -Recurse |
     Where-Object { !$_.PSIsContainer } |
     Select Name,Fullname,Length
    

    【讨论】:

    • 这仍然会将所有文件对象扔到内存中...请参阅@ojk 的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多