Home > other >  Powershell send-mailmessage with body text not working in batch script
Powershell send-mailmessage with body text not working in batch script

Time:04-16

Need help converting PowerShell commands to run in batch. I can get the following to run fine as .ps1:

$filecontent = Get-Content -path C:\temp\status.txt | Out-string
Send-MailMessage  -to   "[email protected]"   -from   "[email protected]"  -subject "STATUS: PASS"      -body "$filecontent" -smtpServer mail2.co.test.ca.us

When I put it into a batch:

PowerShell  -command "$filecontent = Get-Content -path C:\temp\status.txt | Out-String" ^
Powershell  -command Send-MailMessage        ^
    -to      \"[email protected]\"        ^
    -from    \"[email protected]\"       ^
    -subject \"STATUS: PASS \"      ^
    -body    \"$filecontent\" ^
    -smtpServer     mail2.co.test.ca.us

I get this error:

Out-String : A positional parameter cannot be found that accepts argument 'Send-MailMessage'.
At line:1 char:55
  ... tatus.txt | Out-String Send-MailMessage -to "[email protected]" -from " ...
      CategoryInfo          : InvalidArgument: (:) [Out-String], ParameterBindingException
      FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.OutStringCommand

Is the only way to make this work in a batch is to put the original PowerShell syntax into a .ps1 and call it from the batch? The send-mail portion works fine. Tried the $filecontent line without " and -Raw instead of the pipe and Out-string.

CodePudding user response:

You should try to put it in one command :

PowerShell  -command "$filecontent = Get-Content -path d:\temp\status.txt | Out-String; Send-MailMessage -to \"[email protected]\" -from \"[email protected]\" -subject \"STATUS: PASS \"  -body \"$filecontent\" -smtpServer     mail2.co.test.ca.us"

Because in the second command $filecontent no longer exist.

  • Related