Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'System.OutOfMemoryException' while looping through array in powershell

Tags:

powershell

I was trying to write a function that to look for pool tags in .sys files. I created an array of all the directories that had .sys files then looped through them using the sysinternals Strings utility.

This is the array:

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

This was my first attempt at a loop:

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}   
}

I found some references to the error indicating that in foreach loops, all of the information is stored in memory until it completes its processing.

So I tried this:

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}       
}

But it had the same result. I've read that sending an item at a time across the pipeline will prevent this error/issue, but I'm at a loss on how to proceed. Any thoughts?

like image 869
Hector Luna Avatar asked Jul 01 '26 14:07

Hector Luna


1 Answers

Yeah, it is usually better to approach this problem using streaming so you don't have to buffer up a bunch of objects e.g.:

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

Also, I'm not sure why you're using Invoke-Command when you can invoke strings and findstr directly. You typically use Invoke-Command to run a command on a remote computer.

like image 135
Keith Hill Avatar answered Jul 04 '26 23:07

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!