Executing inline powershell script

无人久伴 提交于 2019-12-12 02:13:50

问题


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.


回答1:


  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}"




回答2:


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.



来源:https://stackoverflow.com/questions/41910267/executing-inline-powershell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!