Send-MailMessage cmdlet在我将其设置为变量时运行

时间:2013-09-06 16:21:56

标签: powershell variable-assignment

我正在尝试将Send-MailMessage设置为变量。输入Powershell后,它会自动发送电子邮件。我的语法:

$EmailTo = "To"
$EmailFrom = "From"
$EmailSmtp = "smtp"
$EmailComputer = "$Env:Computername"
$EmailSubject = "Warning! $Emailcomputer had errors!"
$EmailCopyWarning = Send-MailMessage -to $Emailto -from $Emailfrom -subject $Emailsubject -smtpserver $Emailsmtp -body $CopyFalse
$EmailSvcWarning = Send-MailMessage -to $Emailto -from $Emailfrom -subject $Emailsubject -smtpserver $Emailsmtp -body $CCMExecNoSvc

上面设置的所有变量都在我的代码中正确显示,但是当我尝试为$ emailcopywarning和$ emailsvcwarning设置变量时,他们会立即向我发送电子邮件。我的意图是只在发生错误时才发送电子邮件。非常感谢!

2 个答案:

答案 0 :(得分:0)

如果你想"保存"将PowerShell代码作为稍后执行的变量,需要创建scriptblock

$EmailCopyWarning = [scriptblock]::Create("Send-MailMessage -to $Emailto -from $Emailfrom -subject $Emailsubject -smtpserver $Emailsmtp -body $CopyFalse");

然后执行它:

$EmailCopyWarning.Invoke();

但这并不是真正你应该做的事情。编写错误检测代码,如果检测到错误,只需发送电子邮件即可。如果您的目的是模块化脚本,或者调用您已定义发送的功能。

答案 1 :(得分:0)

function SendCopyWarning {Send-MailMessage -to $ Emailto -from $ Emailfrom -subject $ Emailsubject -smtpserver $ Emailsmtp -body $ CopyFalse}

if(test-path yada){do this} else {do this; SendCopyWarning}