Powershell get-childitem 需要大量内存

gre*_*orn 3 directory powershell

我的问题与元过滤器上发布的问题几乎相同。

我需要使用 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 }
Run Code Online (Sandbox Code Playgroud)

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

最好的问候,新手

ojk*_*ojk 5

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

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

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