使用批处理文件将“主题”和“正文”参数传递到Powershell电子邮件脚本

时间:2018-08-23 14:59:33

标签: powershell

我有一个powershell脚本,

[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
$Mail_to="Jill.maclaurin@ca.ibm.com"
$Mail_from="shuddha.roy@gmail.com"
$Subject = "Test"
$Body = "Test Body"
$SMTPServer = "smtp.sendgrid.com"

Send-MailMessage -SmtpServer $SMTPServer -Port 587 -UseSsl -From $Mail_from -To $Mail_to -Subject $Subject -BodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)

现在我希望从批处理文件中获取$subject$Body的值,并使用该批处理文件运行powershell脚本,该怎么做?

1 个答案:

答案 0 :(得分:1)

在脚本的开头添加一个Param部分,您可以将默认值用作必需参数,保存文件。

Param(
$Subject = "Test",
$Body = "Test Body"
)

[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
$Mail_to="Jill.maclaurin@ca.ibm.com"
$Mail_from="shuddha.roy@gmail.com"
$SMTPServer = "smtp.sendgrid.com"

Send-MailMessage -SmtpServer $SMTPServer -Port 587 -UseSsl -From $Mail_from -To $Mail_to -Subject $Subject -BodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)

使用所需的参数从批处理文件中调用PS1文件,例如:

powershell script.ps1 MySubject MyBody