Hello, I have the following script on my Exchange server for determining mailbox sizes. When I run it manually, it works fine. However, when I schedule it to run daily, it sends the same file to me every time. So, it's not writing over the text file in c:\scripts. If I delete the file manually, then run the script I get a new result file. I've tried to add a remove-item in the script, but I get the following error when I do:
Remove-Item : Cannot remove item C:\scripts\mailboxes.txt: The process cannot access the file 'C:\scripts\mailboxes.txt' because it is being used by another process.
At C:\scripts\SendMailboxStats.ps1:24 char:12
+ remove-item <<<< c:\scripts\mailboxes.txt -force
+ CategoryInfo : WriteError: (C:\scripts\mailboxes.txt:FileInfo)
[Remove-Item], IOException
+ FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
Remove-Item : Cannot remove item C:\scripts\mailboxes.txt: The process cannot access the file 'C:\scripts\mailboxes.txt' because it is being used by another process.
At C:\scripts\SendMailboxStats.ps1:24 char:12
+ remove-item <<<< c:\scripts\mailboxes.txt -force
+ CategoryInfo : WriteError: (C:\scripts\mailboxes.txt:FileInfo)
[Remove-Item], IOException
+ FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
Code:
###Send mailbox statistics script
###First, the administrator must change the mail message values in this section
$FromAddress = "mailboxreport@foo.com"
$ToAddress = "alewis@foo.com"
$MessageSubject = "Mailbox Size Report"
$MessageBody = "Attached is the current list of mailbox sizes."
$SendingServer = "foo.net"
###Now get the stats and store in a text file
Get-MailboxStatistics | Sort-Object TotalItemSize -Descending | ft DisplayName,@{label="TotalItemSize(KB)";expression={$_.TotalItemSize.Value.ToKB()}}, ItemCount -auto > c:\scripts\mailboxes.txt
###Create the mail message and add the statistics text file as an attachment
$SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress,
$MessageSubject, $MessageBody
$Attachment = New-Object Net.Mail.Attachment("c:\scripts\mailboxes.txt")
$SMTPMessage.Attachments.Add($Attachment)
###Send the message
$SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
$SMTPClient.Send($SMTPMessage)
remove-item c:\scripts\mailboxes.txt -force
exit