Best way to check if multiple files exists before upload

Advertisement

phoeneous_
Guest

Best way to check if multiple files exists before upload

I have an automated process that uploads XML files to SFTP server and makes a copy of the files in local directory. The uploaded files are then downloaded at an automated interval by another server and removed from SFTP. Sometimes the files don't get removed for whatever reason. To avoid uploading the same files again, I need to check if the files already exist before uploading them to avoid multiple downloads once the service is resumed on the other server.

I've read this https://winscp.net/eng/docs/library_session_fileexists but the example is for a single file with the filename hardcoded in the $remotePath variable.

But what if I'm working with multiple files? How do I check if each one exists?

I attempted it below but it fails to see that a file does exist in remote directory. I'm pretty sure the issue is my if statement...
# Connect
$session.Open($sessionOptions)
 
$localFiles = Get-ChildItem -Name $localPath | Where {$_ -Like '*.xml'}
Write-Host ("localFiles are $localFiles")
 
$remoteList = $session.ListDirectory($remotePath)
$remoteFiles = $remoteList.Files.Name | Where {$_ -Like '*.xml'}
Write-Host ("remoteFiles are $remoteFiles")
 
foreach ($file in $localFiles)
{
    if ($session.FileExists($remoteFiles))
    {
        Write-Host ("$file already exists in $remotePath")
    }
    if (!($session.FileExists($remoteFiles)))
    {
        Write-Host ("$file does not exist in $remotePath")
    }
}
.....
And the output from PowerShell ISE console:
PS C:\Windows\system32> tester.ps1
localFiles are 4.xml 5.xml
remoteFiles are 2.xml 4.xml testertester.xml 3.xml
4.xml does not exist in /Download/
5.xml does not exist in /Download/

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
41,454
Location:
Prague, Czechia

Re: Best way to check if multiple files exists before upload

You can do:
$files =
    $session.EnumerateRemoteFiles(
        "/remote/path", $null, [WinSCP.EnumerationOptions]::None);
 
if ([Linq.Enumerable]::Any($files))
{
    ...
}
See https://winscp.net/eng/docs/script_checking_file_existence#library

Though it really looks like could use Session.SynchronizeDirectories instead:
https://winscp.net/eng/docs/library_session_synchronizedirectories

Reply with quote

Advertisement

You can post new topics in this forum