From b992ad2234ab8fb20805bea1ea71f88386af2944 Mon Sep 17 00:00:00 2001 From: igor04091968 Date: Thu, 7 May 2026 23:52:03 +0300 Subject: [PATCH] feat(dlp): graceful shutdown and COM cleanup for email collector --- windows/email-outbound-collector.ps1 | 82 +++++++++++++++++----------- 1 file changed, 51 insertions(+), 31 deletions(-) diff --git a/windows/email-outbound-collector.ps1 b/windows/email-outbound-collector.ps1 index cbbb111..d7f4d94 100644 --- a/windows/email-outbound-collector.ps1 +++ b/windows/email-outbound-collector.ps1 @@ -610,45 +610,65 @@ if ($useOutlook) { # Main loop # --------------------------------------------------------------------------- -while ($true) { - try { - Flush-Wal - Write-CollectorHealth -Status 'running' - if (-not $script:Policy.defaults.enabled) { - Start-Sleep -Seconds $resolvedPollSeconds - continue - } - - if ($useOutlook) { - if (-not $outlookReady) { - $outlookReady = Initialize-OutlookCom +try { + while ($true) { + try { + Flush-Wal + Write-CollectorHealth -Status 'running' + if (-not $script:Policy.defaults.enabled) { + Start-Sleep -Seconds $resolvedPollSeconds + continue } - if ($outlookReady) { + + if ($useOutlook) { + if (-not $outlookReady) { + $outlookReady = Initialize-OutlookCom + } + if ($outlookReady) { + try { + Poll-OutlookSentItems + } + catch { + Write-CollectorLog ("outlook poll error: {0}" -f $_.Exception.Message) + $outlookReady = $false + $script:OutlookApp = $null + $script:OutlookNamespace = $null + $script:SentFolder = $null + } + } + } + + if ($useSmtp) { try { - Poll-OutlookSentItems + Poll-SmtpConnections } catch { - Write-CollectorLog ("outlook poll error: {0}" -f $_.Exception.Message) - $outlookReady = $false - $script:OutlookApp = $null - $script:OutlookNamespace = $null - $script:SentFolder = $null + Write-CollectorLog ("smtp poll error: {0}" -f $_.Exception.Message) } } } + catch { + Write-CollectorLog ("collector error: {0}" -f $_.Exception.Message) + } - if ($useSmtp) { - try { - Poll-SmtpConnections - } - catch { - Write-CollectorLog ("smtp poll error: {0}" -f $_.Exception.Message) - } + Start-Sleep -Seconds $resolvedPollSeconds + } +} +finally { + Write-CollectorHealth -Status 'stopped' + try { + if ($null -ne $script:SentFolder) { + [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($script:SentFolder) + $script:SentFolder = $null + } + if ($null -ne $script:OutlookNamespace) { + [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($script:OutlookNamespace) + $script:OutlookNamespace = $null + } + if ($null -ne $script:OutlookApp) { + [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($script:OutlookApp) + $script:OutlookApp = $null } } - catch { - Write-CollectorLog ("collector error: {0}" -f $_.Exception.Message) - } - - Start-Sleep -Seconds $resolvedPollSeconds + catch {} }