0

I have a powershell script ,

[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
$Mail_to="[email protected]"
$Mail_from="[email protected]"
$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)

Now i want the $subject and $Body value to be obtained from a batch file and run the powershell script using that batch file, How to do it?

2
  • You need to add some parameters (e.g. -Subject and -Body) to your script, then call it like this: MyScript.ps1 -Subject "some text" -Body "more text". More info here: about_Functions Commented Aug 23, 2018 at 15:11
  • What do you mean, "subject and body obtained from a batch file"? It's not clear what you're trying to accomplish. Commented Aug 23, 2018 at 15:12

1 Answer 1

1

Add to the start of the script a Param Section, you can use default value for the required parameters, save the file.

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

[System.Net.ServicePointManager]::SecurityProtocol = 'TLS12'
$Mail_to="[email protected]"
$Mail_from="[email protected]"
$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)

Call the PS1 file from the batch file using the required paramters, e.g:

powershell script.ps1 MySubject MyBody
Sign up to request clarification or add additional context in comments.

1 Comment

getting the below error "S:\prod\mhedqa\RWScripts>powershell S:\prod\mhedqa\RWScripts\EmailUpdate.ps1 "TEST1" "TEST1 Body" Send-MailMessage : Cannot validate argument on parameter 'Subject'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. At S:\prod\mhedqa\RWScripts\EmailUpdate.ps1:17 char:99 + ... -UseSsl -From $Mail_from -To $Mail_to -Subject $EmailSubject -BodyAs ... + ~~~~~~~~~~~~~ "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.