经过大量错误和编辑后,我通过命令提示符获得了发送邮件。 下面的迭代完美地发送了电子邮件。
powershell Send-MailMessage -From " `<user@domain>`" -To " `<user@domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: $env:computername. List of deleted files is attached.' -Attachments 'C:somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'
但是,这不会获取体内的computername
。我尝试直接在 powershell 中运行此命令,它适用于正文中的计算机名变量。
为了让它简单地发送邮件,我已经尝试过这样做
powershell -command "command"
或powershell -command "{command}
或powershell -command "& {command}"
等等,它甚至不发送 出电子邮件。
由于我现在已成功发送电子邮件,因此我需要在正文文本中包含计算机名。
在参数值两边使用双引号以扩展包含变量。
即:
-Body "Some body with alert regarding Host: **$env:computername**. ..."
相关阅读。
您在问题中的命令行和您自己的答案依赖于这样一个事实,即 powershell 当前具有默认(位置 0)参数-Command
,
但这从PowerShell 6.0.0beta3
更改为-File
- 您应该明确使用至少
-C
作为最短-Command
的缩写 . - 为了加快执行速度,我会使用附加参数
-NoProfile
或短-NoP
和-NonInteractive
或-NonI
- 要阻止 CMD 尝试解释任何参数/参数,您应该将它们全部双引号 - 并使用反斜杠
"
转义任何必要的内部双引号,同时如果可能的话,还要用单引号替换双引号。
所以我建议:
powershell -NoP -NonI -C "Send-MailMessage -From "SomeWeb-Prod@domain.com" -To "fromuser@domain.com" -Subject 'Some notification for SomeWeb-Prod' -Body 'Some Alert for Host: %computername% with IP: %NetworkIP% at %time%. details in attached file.' -Attachments 'C:somefile.txt' -Priority High -dno onFailure -SmtpServer 'smtp.domain.com'"
或者,(正如您自己部分发现的那样):
powershell -NoP -NonI -C "Send-MailMessage -From 'SomeWeb-Prod@domain.com' -To 'fromuser@domain.com' -Subject 'Some notification for SomeWeb-Prod' -Body 'Some Alert for Host: %computername% with IP: %NetworkIP% at %time%. details in attached file.' -Attachments 'C:somefile.txt' -Priority High -dno onFailure -SmtpServer 'smtp.domain.com'"
>"$env:computername"
对我不起作用。它只是将其打印为$env:计算机名
%computername%
奏效了。
这是现在对我有用的东西。
powershell Send-MailMessage -From " `<user@domain.com>`" -To " `<user@domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: %computername%. Some file is attached.' -Attachments 'C:somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'
更新:
上面的命令在Win7上运行良好,但在服务器2012上出现错误。 最后,这就是在 win 2012 上起作用的原因
powershell "Send-MailMessage -From "SomeWeb-Prod@domain.com" -To "fromuser@domain.com" -Subject 'Some notification for SomeWeb-Prod' -Body 'Some Alert for Host: %computername% with IP: %NetworkIP% at %time%. details in attached file.' -Attachments 'C:somefile.txt' -Priority High -dno onFailure -SmtpServer 'smtp.domain.com'"
它对我有用,通过在变量周围使用双引号。
我正在使用批处理脚本来调用powershell发送邮件消息
批处理脚本:send_email.bat
C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -windowstyle hidden -command 'E:pathsend_email.ps1
Pwershell Script send_email.ps1
Send-MailMessage -From "noreply@$env:computername" -To '<target_email@example.com>' -Subject 'Blah Blah' -SmtpServer 'smtp.domain.com' -Attachments 'E:pathfile.log' -BODY "Blah Blah on Host: $env:computername "