Post a reply

Options
Add an Attachment

If you do not want to add an Attachment to your Post, please leave the Fields blank.

(maximum 10 MB; please compress large files; only common media, archive, text and programming file formats are allowed)

Options

Topic review

phoeneous_

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/