Powershell get-childitem 需要大量内存

Powershell get-childitem needs a lot of memory

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

我需要使用 PowerShell 脚本扫描大量文件。问题是 "Get-ChildItem" 函数似乎坚持将整个文件夹和文件结构推送到内存中。由于该驱动器在 30,000 多个文件夹中有超过一百万个文件,因此脚本需要大量内存。

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 }

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

此致, 格林霍恩

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

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

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

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

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