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 = "[email protected]",
$Mailfrom = "[email protected]",
$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 }"
this script must be missing stuff. You are using Param, which must be the first line in script block. What is likely happening is that powershell is looking at this as if you typed
You are missing a function declaration and braces (if that's what you are trying to do). There is no function in the page you mention as source
Could it be an issue with quotes and/or escaping characters? Maybe the difference is not in the one line added/removed, but in the way you run it?
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:
It may not be that one line that is the issue...just when it is commented out the whole thing breaks, so the actual error doesn't get a chance to surface.
Try breaking this script up into multiple lines, assigning variables and properties separately, and you should be able to narrow down the issue.