I am running reports in batch files on several servers and I need to send emails from those batch files calling a PS1 script. When using a specific set of recipients, subject and body, it is working all fine. The issue is, I need the PS1 script to pick those 3 parameters from what they are in the BAT file as they change in every report. I am a LINUX head so struggling with the logic here and any help is highly appreciated. Thank you
PS1 script... (all the $ variables are defined in the ps1 script and the $arg1,2,3 are defined as below)
$arg1=$args[0]
$arg2=$args[1]
$arg3=$args[2]
Send-MailMessage -From $MailFrom -To $args1 -Subject $args2 -Body $arg3 -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $MailCredential
Batch script
SET ROOT_DIR=\\FILEZ01.PATH.COM\INFO$\\OUTPUT\REPORTS
set FILE_NAME=%s_date%_MY_FILE.txt
set [email protected]
powershell.exe -ExecutionPolicy Unrestricted -Command ". 'C:\Tasks\scripts\SMTP.ps1' -To %REC_LIST% -Subject "ART Delta Patron test" -Body "%ROOT_DIR%\%FILE_NAME%""
CodePudding user response:
In order to make named parameters work, declare a param(...)
block on the first line of the script:
param($To,$Subject,$Body)
Now PowerShell will automatically bind any argument passed to -To
to the $To
variable inside the script.
Since all the parameters are named the same in your script and the target cmdlet, you can pass them all along by splatting $PSBoundParameters
:
Send-MailMessage -From $MailFrom @PSBoundParameters -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $MailCredential
CodePudding user response:
Use $Env:BatchVar instead.
I don't have the time to test or debug this, but in general it should look something like this:
Batch file:
SET ROOT_DIR=\\FILEZ01.PATH.COM\INFO$\\OUTPUT\REPORTS
set FILE_NAME=%s_date%_MY_FILE.txt
SET [email protected]
SET Subject=ART Delta Patron test
SET Body=%ROOT_DIR%\%FILE_NAME%
powershell.exe -ExecutionPolicy Unrestricted -Command ". 'C:\Tasks\scripts\SMTP.ps1' "
PowerShell:
Send-MailMessage -From $MailFrom -To $Env:To -Subject $Env:Subject -Body $Env:Body -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $MailCredential