How to check if PSFTP process returns 0 with batch file

NerdyBird picture NerdyBird · Feb 19, 2014 · Viewed 8.5k times · Source

I am writing a batch script with takes files from a directory and copies them remotely using psftp.

Here is the line that does all the magic:

echo n | psftp.exe [email protected] -i id_rsa.ppk -v -b psftp-rules.txt -bc >> c:\log-file.txt

As you can see, the psftp.exe is called and the authenticated via a rsa key. The putting takes place in the psftp-rules.txt and the activity is recorded in the log-file.txt.

What I need is a function that will check for a return code, and if there is any failure, to write the error to the log file and then quit.

What I am looking for is perhaps setting a variable for this return code. Then I imagine an if statement that is the variable equals 1 to end the script and echo an error message into a log.

The issue I am seeing is that once the line above is ran, the batch script if not involved. Any assistance would be appreciated.

Answer

David Ruhmann picture David Ruhmann · Feb 20, 2014

Check if psftp sets an error code

Check the value of %ErrorLevel% right after the function has run. Run this in both a successful workflow and failure workflow to verify that the ErrorLevel was set upon failure.

echo %ErrorLevel%
echo n | psftp.exe [email protected] -i id_rsa.ppk -v -b psftp-rules.txt -bc >> c:\log-file.txt
echo %ErrorLevel%

Update

Store the ErrorLevel in a variable and evaluate

echo n | ...
set "ExitCode=%ErrorLevel%"
if "%ExitCode%"=="1" echo This is my error message for error 1 > c:\log-file.txt & exit /b %ExitCode%

If you want to capture all positive ErrorLevels and echo the same message use the following if statement.

echo n | ...
if ErrorLevel 1 echo This is my error message for error 1+ > c:\log-file.txt & exit /b %ErrorLevel%