Checking file existence

Remote file existence

Using WinSCP .NET Assembly

Use method Session.FileExists from WinSCP .NET assembly.

The following example uses a PowerShell script. If you have another preferred language, you can easily translate it.

$remotePath = "/home/user/test.txt"
 
if ($session.FileExists($remotePath))
{
    Write-Host ("File {0} exists" -f $remotePath)
}

See complete PowerShell example for Session.FileExists.

If you are not looking for a specific file, but for any file matching a mask (e.g. *.txt), you can use the Session.EnumerateRemoteFiles.

Advertisements:

Using WinSCP Scripting

You can use a stat command in the (default) option batch abort mode to query file attributes. If the file does not exist, the stat command fails and so does the script. Then, test WinSCP exit code to determine, if the file exists or not.

@echo off
 
set REMOTE_PATH=/home/user/test.txt
winscp.com /command ^
    "open mysession" ^
    "stat %REMOTE_PATH%" ^
    "exit"
 
if %ERRORLEVEL% neq 0 goto error
 
echo File %REMOTE_PATH% exists
rem Do something
exit /b 0
 
:error
echo Error or file %REMOTE_PATH% not exists
exit /b 1

To check for existence of any file matching a mask, instead of a specific file, enable option failonnomatch on mode and use ls mask command, instead of stat name command:

set REMOTE_PATH=/home/user/*.txt
winscp.com /command ^
    "open mysession" ^
    "option failonnomatch on" ^
    "ls %REMOTE_PATH%" ^
    "exit"

Local file existence

Further Reading

 
  script_checking_file_existence.txt · Last modified: by martin
 

Search Documentation

This page

Donate

About donations

$9   $19   $49   $99

About donations

Recommend

Associations

Site design by Black Gate