I've got a Powershell script that I'm trying to set up so it can send an Exchange status email to me everyday. I've got the script working just fine when I run it manually from an EMS console window, but when I try to add it as a scheduled task, I need to add the line Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin at the top. This addition seems to be causing a problem, as when I try to run the script from the task window, I get this error:
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
param(
$MailServer = "mailserver",
$MailTo = "me@company.com",
$Mailfrom = "me@company.com",
$Subject = "Exchange System Status " + (Get-Date))
$body = Get-MailboxDatabase -Status | select Name,LastDifferentialBackup,LastFullBackup |
Out-String
$body2 = Get-ExchangeServer | where {$_.ServerRole -Match "HubTransport"} | Get-Queue | select Identity,Status,MessageCount,NextHopDomain | Out-String
$email = new-object system.net.mail.mailmessage
$email.to.add($MailTo)
$email.from = $Mailfrom
$email.subject = $Subject
$email.isbodyhtml = $False
$email.body = $body,$body2
$client = new-object system.net.mail.smtpclient $mailserver
$client.send($email)
When I have that PSSnapin line at the top and I run the task, I get this error: Invalid assignment expression. The left hand side of an assignment operator needs to be something that can be assigned to like a variable or a property
Taking the line out and then trying to run the task obviously wouldn't work since it doesnt have the Exchange snap in the default powershell window. I'm calling the script using a batch file in the scheduled task with the command: Powershell -command "& {C:\Scripts\exchemail.ps1 }"
Best Answer
Instead of trying to figure out what's wrong, I'll suggest what works 100% for me.
This script gets mailbox stats, but you can adapt it to do whatever you want.
Contents of Get-MailboxStatistics.ps1:
This is run by a scheduled batch file containing this line: