Tuesday, October 27, 2020

// // Leave a Comment

Send PowerShell email from Windows batch file without creating separate email.ps1 file

In this article, we will see how we can send a PowerShell email from the Windows batch file without creating any separate email.ps1 file.

Suppose you have a batch script to perform a certain task and once that task is completed you want to be notified through an email alert.

One way to achieve this is by creating a separate email.ps1 file and calling that email.ps1 from your batch file. You can find multiple solutions on Google for this approach. But if the purpose is just to send an email alert with an attachment like a log file or with some text in the email body then why to go for creating another email.ps1 file.

You can simply insert the below code at the end of your batch script or with some conditional statements to send an email alert within the batch script:

:: Send Email using PowerShell
Powershell.exe -command "& {Send-MailMessage -From Admin@company.com -To users@company.com -Subject 'Prod Hyperion Backup Copy to DR for DR Rehearsal' -SmtpServer 'smtpserver.company.com' -Body 'PFA log file consisting of details of PROD Hyperion Backup files copied to DR Network path' -Attachments 'E:\Data\Prod_DR_Copy.log'}"


Here:

  • '&' is the call operator. The call operator (&) allows you to execute a command, script, or function.
  • Change the parameter values (To, From, Subject, Body, SmtpServer, Attachments) as per your requirement.  

There are many other parameters that you can add to the above command as per your need. Read this Link1 and Link2 for more details.

Make sure you copy and paste the above code as it is. Because on some occasions, I have noticed that using double quotes ("") in place of single quotes ('') will throw PowerShell error:

Send-MailMessage :  A positional parameter cannot be found that accepts arguement "SomeWord"...

It happens because the PowerShell command processor strips your double quotes and your "SomeWord" appears as a parameter to Send-MailMessage. So to avoid this error, you need to escape double quotes in your command.

The best way is to use single quotes ('') in your command as given above but If you really want to use double quotes for whatsoever reason, then use it like below by escaping double quotes ("") in -Subject and -Body parameters:

Powershell.exe -command "& {Send-MailMessage -From Admin@company.com -To users@company.com -Subject \"Prod Hyperion Backup Copy to DR for DR Rehearsal\" -SmtpServer "smtpserver.company.com" -Body \"PFA log file consisting of details of PROD Hyperion Backup files copied to DR Network path\" -Attachments "E:\Data\Prod_DR_Copy.log"}"

That's all for this post.


I hope this article has helped you. 
Your suggestions/feedback are most welcome.

Keep learning and Have a great day!!!

0 comments:

Post a Comment