Documentation » Using WinSCP » Guides » Scripting/Automation »

Conditional Processing in Automation

When automating an operation with WinSCP, you may want to perform it only when a certain condition is met. Typically you may want to test if a particular file exists before attempting to transfer it.

Advertisement

Using WinSCP .NET Assembly

Particularly for complex conditions or conditions involving remote files, using WinSCP .NET assembly is the easiest and the recommended approach.

An example of PowerShell script that checks if a remote file exists before downloading it:

$remotePath = "/home/user/test.txt"
$localPath = "C:\download\test.txt"
 
if ($session.FileExists($remotePath))
{
    Write-Host "File $remotePath exists, downloading"
    $session.GetFiles($remotePath, $localPath).Check()
}
else
{
    Write-Host "File $remotePath does not exist"
}

See also:

Advertisement

Conditions in a Batch File

If you do not want to use .NET assembly, for simple conditions or conditions involving local files, you may be able to move the condition outside of WinSCP script into a wrapper batch file.

For example you can use an if command to test a local file existence before uploading it:

if exist c:\upload\test.txt winscp.com /ini=nul /log=upload.log /script=upload.txt

If you need different conditions for individual script commands, you can generate the WinSCP script file on the fly step by step:

@echo off
set FILE1=c:\upload\test.txt
set FILE2=c:\other\file.txt
 
(
  echo open sftp://user:password@example.com/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx..."
  if exist %FILE1% echo put %FILE1%
  if exist %FILE2% echo put %FILE2%
  echo exit
) > upload.txt
 
winscp.com /ini=nul /log=upload.log /script=upload.txt

See also:

Last modified: by martin