I wrote a script to go through a list of network shares and find strings in specific files, with multi-threads using ForEach-Object -Parallel
in powershell 7.
The problem is that even if i use the garbage collector or remove-variable
, after a few minutes the memory on my computer is near full.
Code :
$ErrorActionPreference= 'silentlycontinue'
$available_share_list = "share_list.txt"
function Iterate_over_share_t ()
{
$unc = Get-Content $available_share_list
$unc | foreach-Object -Parallel {
$share=$_
$share_safe = $share.replace("\","-")
$share_safe = $share_safe.replace("$","")
$share_safe = $share_safe.replace(":","")
Get-ChildItem -Recurse $share -Depth 4 |
ForEach-Object{
function parseFile() {
param(
$ext
)
$extension=$ext[0]
$unc=$ext[1]
$content = Get-Content $unc
$date = Get-Item $unc; $date_csv = $date.LastWriteTime.ToString("yyyy-MM-dd HH:mm")
## Here i write to files if string is found in $content
## And i then remove according variables
Write-Output "string" | myfile.txt
Remove-Variable -Name <var> -ErrorAction SilentlyContinue
## I then force the garbage collector
if($found -eq $true){
[System.GC]::Collect()
[System.GC]::GetTotalMemory('forcefullcollection') | out-null
[System.GC]::GetTotalMemory($true) | out-null
}
}
$file = $_.FullName -replace '\r?\n\z'
parseFile("txt",$file)
Remove-Variable -Name $file -ErrorAction SilentlyContinue
}
Remove-Variable -Name $share -ErrorAction SilentlyContinue
Remove-Variable -Name $share_safe -ErrorAction SilentlyContinue
[System.GC]::Collect()
[System.GC]::GetTotalMemory('forcefullcollection') | out-null
[System.GC]::GetTotalMemory($true) | out-null
echo "[v] : $share"
} -ThrottleLimit 50
}
So i was wondering if anyone experienced this issue, or if i should just change to another language ahah.
Have a nice day, Q.