-1

I'm testing with a PowerShell script (where I'm testing copy and paste over FTPs using WinSCP), and in parallel I'm configuring the following code for sending mail in case of error on any of the put tasks, get....

This is the code:

@echo off
 
set WINSCP_LOG=C:\Users\Administrator\Desktop\WinSCP.log

rem Run WinSCP script

    "C:\Program Files (x86)\WinSCP\WinSCP.com" ^
    /log=%WINSCP_LOG% /ini=nul ^
    /command ^
        "open sftp://example:%%r%%21@he.example.es/ -hostkey=""ssh-rsa 2048 pRzlrJ27Zasd7"09¡^
        "lcd C:\Users\Administrator\Desktop" ^
        "cd /ftp-files/O1" ^
        "put examplefile.txt" ^
        "exit

rem Check WinSCP result and prepare the email message
if %ERRORLEVEL% equ 0 (
  set WINSCP_SUBJECT=Success
  set WINSCP_MESSAGE=The files were uploaded successfully.
  set WINSCP_CODE=0
) else (
  set WINSCP_SUBJECT=Error
  set WINSCP_MESSAGE=Error uploading files, see attached log.
  set WINSCP_CODE=1
)
 
echo %WINSCP_SUBJECT%
echo %WINSCP_MESSAGE%
 
rem Send the email message
 
set SMTP_FROM=no_reply@example.es
set SMTP_TO=bztruster@example.com
set SMTP_SERVER=smtp.office365.com
set SMTP_USERNAME=no_reply@example.es
set SMTP_PASSWORD=Asfaj23@#
 
if exist "%WINSCP_LOG%" set ATTACHMENT=-Attachments '%WINSCP_LOG%'
 
powershell -ExecutionPolicy Bypass Send-MailMessage ^
    -From %SMTP_FROM% -To %SMTP_TO% -Subject '%WINSCP_SUBJECT%' -Body '%WINSCP_MESSAGE%' ^
    %ATTACHMENT% -SmtpServer %SMTP_SERVER% -UseSsl ^
    -Credential (New-Object System.Management.Automation.PSCredential ^
        ('%SMTP_USERNAME%', (ConvertTo-SecureString '%SMTP_PASSWORD%' -AsPlainText -Force)))
 
exit /b %WINSCP_CODE%

Where or how could I get more context on the errors in order to know the reason for the failure within the received mail?

Thanks for your help!

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Bztruster
  • 59
  • 1
  • 1
  • 3

1 Answers1

-1

You are sending the wrong parameters to powershell.exe binary. Run the following to understand the parameters accepted and the syntax needed:

powershell.exe /?

For your particular needs, you can use the parameter -Command, e.g:

powershell -ExecutionPolicy Bypass -Command {Send-MailMessage ^
-From %SMTP_FROM% -To %SMTP_TO% -Subject '%WINSCP_SUBJECT%' -Body '%WINSCP_MESSAGE%' ^
%ATTACHMENT% -SmtpServer %SMTP_SERVER% -UseSsl ^
-Credential (New-Object System.Management.Automation.PSCredential ^
    ('%SMTP_USERNAME%', (ConvertTo-SecureString '%SMTP_PASSWORD%' -AsPlainText -Force)))}
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
JIF
  • 9
  • 1
  • Originally I've upvoted your answer, as `-Command` indeed seems to be missing in the OPs code. But now testing it, I see that actually OP's syntax works and yours does not. The `-Command` does not seem to be required (although it's not clear from the documentation). And adding the curly brackets breaks it completely. – Martin Prikryl Jan 28 '22 at 08:56