2

I'm trying to invoke an inline powershell script from Task Scheduler to send an email when a particular event is triggered. I can't use the native 'Send an e-mail' action in the Task Scheduler action window because the SMTP server requires SSL and there's no way to specify this in the action window. So I'm looking to 'Start a program' and invoke something to send email but I want to avoid using 3rd party applications such as sendEmail if possible so was hoping to be able to invoke an inline powershell script similar to the following.

Setting the 'Program/script' field to powershell and the arguments field to:

-Command "{Send-MailMessage -From "Name <name@domain.com>" -To "name@domain.com" -Subject "Test Subject" -Body "Test body at $(Get-Date -Format "dd/MM/yyyy")." -SmtpServer "smtp.domain.com" -UseSSL}"

This obviously doesn't work due to the nested quotes etc, so I've been trying different variations in command prompt, but I can't for the life of me figure out which characters I need to escape and how to escape them.

Any help would be much appreciated.

sthounsell
  • 45
  • 1
  • 1
  • 6
  • 2
    Possible duplicate of [Powershell - escaping string passed to child process](http://stackoverflow.com/questions/34276662/powershell-escaping-string-passed-to-child-process) – user4003407 Jan 28 '17 at 13:44

2 Answers2

9
  1. Just take a look to the example section of "powershell /?" ...

PowerShell -Command "& {Get-EventLog -LogName Application}"


  1. Take a look how to use quotes.

PowerShell -Command "& {Send-MailMessage -From 'Name ' -To 'name@domain.com' -Subject 'Test Subject' -Body ('Test body at {0}.' -f (Get-Date -Format 'dd/MM/yyyy')) -SmtpServer 'smtp.domain.com' -UseSSL}"

Buxmaniak
  • 460
  • 2
  • 4
  • Thanks, that's great. One thing I forgot to say is that I'm trying to put newline characters in the body of the email too - I would normally use 'r'n (had to use single quotes here instead of actual backtick characters due to SO's syntax highlighting) but the backtick characters are being treated as literals as they're inside a single quoted string. Any ideas how I would do that? – sthounsell Jan 30 '17 at 11:41
4

This should work:

powershell -Command 'Send-MailMessage -From "Name <name@domain.com>" -To "name@domain.com" -Subject "Test Subject" -Body "Test body at $(Get-Date -Format "dd/MM/yyyy")." -SmtpServer "smtp.domain.com" -UseSSL'

You can use single quotes around double quotes, and you don't need the curly brackets around the command.

sodawillow
  • 12,497
  • 4
  • 34
  • 44