$Out = "C:\Temp\MailArchivePlan_$(Get-Date -Format yyyyMMdd_HHmm)"
New-Item -ItemType Directory -Path $Out -Force | Out-Null
$Cutoff = (Get-Date).AddDays(-365).ToString("MM/dd/yyyy")
$ResultFile = "$Out\07_MailOlderThan365d_AllUsers.csv"
# Если файл уже есть — удаляем, чтобы не дописать старые данные
if (Test-Path $ResultFile) {
Remove-Item $ResultFile -Force
}
$counter = 0
$headerWritten = $false
Get-Mailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited | ForEach-Object {
$mbx = $_
$counter++
Write-Host "[$counter] Estimate:" $mbx.PrimarySmtpAddress
try {
$estimate = Search-Mailbox -Identity $mbx.PrimarySmtpAddress `
-SearchQuery "(received:<$Cutoff OR sent:<$Cutoff)" `
-EstimateResultOnly `
-ErrorAction Stop
$row = [PSCustomObject]@{
DisplayName = $mbx.DisplayName
Alias = $mbx.Alias
PrimarySmtpAddress = $mbx.PrimarySmtpAddress
Database = $mbx.Database
ArchiveStatus = $mbx.ArchiveStatus
ArchiveDatabase = $mbx.ArchiveDatabase
CutoffDate = $Cutoff
ResultItemsCount = $estimate.ResultItemsCount
ResultItemsSize = $estimate.ResultItemsSize
Error = $null
}
}
catch {
$row = [PSCustomObject]@{
DisplayName = $mbx.DisplayName
Alias = $mbx.Alias
PrimarySmtpAddress = $mbx.PrimarySmtpAddress
Database = $mbx.Database
ArchiveStatus = $mbx.ArchiveStatus
ArchiveDatabase = $mbx.ArchiveDatabase
CutoffDate = $Cutoff
ResultItemsCount = $null
ResultItemsSize = $null
Error = $_.Exception.Message
}
}
if (-not $headerWritten) {
$row | Export-Csv $ResultFile -NoTypeInformation -Encoding UTF8
$headerWritten = $true
}
else {
$row | Export-Csv $ResultFile -NoTypeInformation -Encoding UTF8 -Append
}
# Очистка переменных после каждого ящика
Remove-Variable estimate -ErrorAction SilentlyContinue
Remove-Variable row -ErrorAction SilentlyContinue
Remove-Variable mbx -ErrorAction SilentlyContinue
# Принудительная очистка памяти каждые 50 ящиков
if (($counter % 50) -eq 0) {
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Write-Host "Memory cleanup after $counter mailboxes"
}
}
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Write-Host "Done. Result file:"
Write-Host $ResultFile