I am working on a script that calculates the size of the last 30 days of email for an Exchange 2016 mailbox. I need to get the exact amount. The only way I know to do this is with mailbox-search. I have seen the get-mailboxfolderstatistics script that estimates the size of the last 30 days. That is not sufficient for my needs. The problem that I am having is that search-mailbox will not let me put resultItemSize into a variable. What am I doing wrong? Can this be done another way? Here is what I have.
$server=read-host "Enter server name"
$targetMailbox=read-host "Enter an email address on this network where the search mailbox folders will be created"
$startDate=(get-date).date.ToShortDateString()
$stopDate=(get-date).date.AddDays(-30).ToShortDateString()
$Report=@()
$mailboxes = Get-mailbox -server $server
foreach ($mailbox in $mailboxes) {
write-host "$($mailbox.primarysmtpaddress)"
Pulling Data
$last30daysinMB=((Search-Mailbox -Identity $mailbox -SearchQuery "received:$($startDate)..$($stopDate) OR sent:$($startDate)..$($stopDate)" -TargetMailbox $targetMailbox -TargetFolder "Mailbox Size Script" -estimateResultsOnly).resultItemSize)
$TotalSizeInMB = ($(Get-MailboxStatistics -Identity $Mailbox | Select-Object -ExpandProperty TotalItemSize | Select-Object -ExpandProperty Value) -split '\(| ')[-2].Replace(',','')/1MB -as [int]
#Building report
$ReportObj = New-Object PSobject
Add-Member -InputObject $ReportObj -type NoteProperty -name User -value $mailbox.PrimarySMTPAddress
Add-Member -InputObject $ReportObj -type NoteProperty -name TotalMB -value $TotalSizeInMB
Add-Member -InputObject $ReportObj -type NoteProperty -name Last30DaysMB -value $last30daysinMB
$Report += $ReportObj
}
$Report | Export-Csv -NoTypeInformation -path "C:\Users\$env:username\Desktop\30DaysOfEmailCalculated-$(Get-Date -Format 'MM-dd-yyyy').csv" -force