File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -65,11 +65,11 @@ function Add-CIPPAzDataTableEntity {
6565 try {
6666 # Ensure all property values are not null for string properties
6767 if ($SingleEnt -is [hashtable ]) {
68- foreach ($key in @ ($SingleEnt.Keys )) {
69- if ($null -eq $SingleEnt [$key ]) {
70- $SingleEnt.Remove ($key )
71- }
68+ $keysToRemove = @ ($SingleEnt.Keys | Where-Object { $null -eq $SingleEnt [$_ ] })
69+ foreach ($key in $keysToRemove ) {
70+ $SingleEnt.Remove ($key )
7271 }
72+ $keysToRemove = $null
7373 } elseif ($SingleEnt -is [PSCustomObject ]) {
7474 $propsToRemove = [system.Collections.Generic.List [string ]]::new()
7575 foreach ($prop in $SingleEnt.PSObject.Properties ) {
Original file line number Diff line number Diff line change @@ -110,7 +110,20 @@ function Add-CIPPDbItem {
110110 # Clear batch variables to free memory
111111 $Entities = $null
112112 $Batch = $null
113- [System.GC ]::Collect()
113+
114+ # Capture memory before GC
115+ $MemoryBeforeGC = [System.GC ]::GetTotalMemory($false )
116+
117+ # Force GC between batches to prevent accumulation
118+ [System.GC ]::Collect([System.GC ]::MaxGeneration, [System.GCCollectionMode ]::Forced)
119+ [System.GC ]::WaitForPendingFinalizers()
120+ [System.GC ]::Collect([System.GC ]::MaxGeneration, [System.GCCollectionMode ]::Forced)
121+
122+ # Log memory usage after GC
123+ $MemoryAfterGC = [System.GC ]::GetTotalMemory($false )
124+ $FreedMB = [math ]::Round(($MemoryBeforeGC - $MemoryAfterGC ) / 1 MB , 2 )
125+ $CurrentMemoryMB = [math ]::Round($MemoryAfterGC / 1 MB , 2 )
126+ Write-Information " Batch $ ( [Math ]::Ceiling($ProcessedCount / $BatchSize )) /$ ( [Math ]::Ceiling($TotalCount / $BatchSize )) complete. Processed: $ProcessedCount /$TotalCount | Memory: ${CurrentMemoryMB} MB | Freed: ${FreedMB} MB"
114127 }
115128
116129 }
Original file line number Diff line number Diff line change @@ -32,6 +32,12 @@ function Set-CIPPDBCacheUsers {
3232 Write-LogMessage - API ' CIPPDBCache' - tenant $TenantFilter - message ' Cached users successfully' - sev Debug
3333
3434 } catch {
35+ # Cleanup on error to prevent memory leak
36+ if ($null -ne $Users ) {
37+ $Users.Clear ()
38+ $Users = $null
39+ }
40+ $UsersResponse = $null
3541 Write-LogMessage - API ' CIPPDBCache' - tenant $TenantFilter - message " Failed to cache users: $ ( $_.Exception.Message ) " - sev Error - LogData (Get-CippException - Exception $_ )
3642 }
3743}
You can’t perform that action at this time.
0 commit comments