title: Using 'for' command to find and download the latest file on SFTP server in PSFTP
body: <p>I have gone through the following guide to set up an SSIS package to retrieve a text file located on an SFTP server:</p>
  
  <p><a href="https://www.mssqltips.com/sqlservertip/3435/using-sftp-with-sql-server-integration-services/" rel="nofollow noreferrer">https://www.mssqltips.com/sqlservertip/3435/using-sftp-with-sql-server-integration-services/</a></p>
  
  <p>To summarize, the SSIS package executes PSFTP.exe (A PuTTY tool) which takes the necessary credentials to connect to the server. It also takes a batch file that it executes after connecting. This batch file contains the commands to retrieve the desired text file. To start from the guide, it simply contains a cmd command to change directory, and a get command to retrieve the file:</p>
  
  <pre><code>cmd DataDump
  get TeleMarketingResults.txt
  </code></pre>
  
  <p>All of this works fine.</p>
  
  <p>The issue arises when I try to make this batch file logic more complex as it does not seem to recognize basic keywords. For instance, I would like to modify it to retrieve the most recent file, so I tried adding this:</p>
  
  <pre><code>for /f %%i in ('dir /b/a-d/od/t:c') do set LAST=%%i
  echo The most recently created file is %LAST%
  </code></pre>
  
  <p>but then I get these errors:</p>
  
  <pre><code>psftp: unknown command "for"
  psftp: unknown command "echo"
  </code></pre>
  
  <p>If I execute the batch file manually in a local directory, it works. The issue only occurs when passing it as a parameter to PSFTP.exe. Why is this?</p>