在PowerShell中循环遍历数组时出现'System.OutOfMemoryException'

时间:2012-10-22 22:49:54

标签: powershell

我试图编写一个函数来查找.sys文件中的池标记。我创建了一个包含.sys文件的所有目录的数组,然后使用sysinternals Strings实用程序循环遍历它们。

这是数组:

$paths = Get-ChildItem \\$server\c$ *.sys -Recurse -ErrorAction SilentlyContinue | 
     Select-Object Directory -unique

这是我第一次尝试循环:

foreach ($path in $paths) {

    #convert object IO fileobject to string and strip out extraneous characters
    [string]$path1 = $path
    $path2 = $path1.replace("@{Directory=","")
    $path3 = $path2.replace("}","")
    $path4 = "$path3\*.sys"
    Invoke-Command -ScriptBlock {strings -s $path4 | findstr $string}   
}

我发现了一些错误引用,表明在foreach循环中,所有信息都存储在内存中,直到完成处理。

所以我尝试了这个:

for ($i = 0; $i -lt $paths.count; $i++){
    [string]$path1 = $paths[$i]
    $path2 = $path1.replace("@{Directory=","")
    $path3 = $path2.replace("}","")
    $path4 = "$path3\*.sys"
    Invoke-Command -ScriptBlock {strings -s $path4 | findstr $string}       
}

但它有相同的结果。我已经读过,在整个管道中一次发送一个项目可以防止这个错误/问题,但我不知道如何继续。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

是的,通常使用流媒体解决这个问题会更好,所以你不必缓冲一堆对象,例如:

Get-ChildItem \\server\c$ -r *.sys -ea 0 | Foreach {
    "Processing $_"; strings $_.Fullname | findstr $string}

另外,当您可以直接调用Invoke-Commandstrings时,我不确定您使用findstr的原因。您通常使用Invoke-Command在远程计算机上运行命令。

相关问题