$session.FileExists() always returns true

Advertisement

ristianchrathke
Joined:
Posts:
1
Location:
Denver, CO

$session.FileExists() always returns true

When using the FileExists and GetFileInfo methods, the return value is an empty file instead of an error. The same issue occurs when trying to get a file that doesn't exist: I receive a directory file with a size of 0 created at the time of the call.

Here's my code, omitting session information:
# Set the path to the file that you want to check for on the SFTP server
$filename = "New"+(Get-Date).ToString("yyyyMMdd")+"*.txt"
# $filename="file.txt"
$filePath = "/directory/"+$filename
# Set the local path where you want to download the file
$localPath = "C:\Users\ristianchrathke\Downloads\"
 
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
 
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = $source_host
    UserName = $source_username
    Password = $source_password
    SshHostKeyFingerprint = "xxxxxxxxxxx"
}
 
$session = New-Object WinSCP.Session
$session.Open($sessionOptions)
 
echo "connection established"
 
# Set up a loop to check for the file every 15 minutes
while ($true) {
    # Check if the file exists on the SFTP server
    if ($session.FileExists($filePath)) {
        # Download the file to the specified local path
        $transferResult = $session.GetFiles($filePath, $localPath+"*")
        $transferResult.Check()
        echo "File downloaded"
 
        # Disconnect from the SFTP server
        $session.close()
        echo "session closed"
        # Break out of while loop
        break
    }
    echo "file not found, waiting 15 minutes before next filecheck..."
 
    # Wait for 15 minutes before checking again
    Start-Sleep -Seconds 900
}
 
# Get yesterday's date
$yesterday = (Get-Date).AddDays(-1).ToString("yyyyMMdd")
 
# Rename the downloaded file to "BAI_" followed by yesterday's date
Rename-Item "$localPath\$filename" "New$yesterday.txt"

Reply with quote

Advertisement

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

Re: $session.FileExists() always returns true

That's likely an issue with your server.

If you want us to confirm/investigate this, please attach a full session log file showing the problem (using the latest version of WinSCP).

To generate the session log file, set Session.SessionLogPath. Submit the log with your post as an attachment. Note that passwords and passphrases not stored in the log. You may want to remove other data you consider sensitive though, such as host names, IP addresses, account names or file names (unless they are relevant to the problem). If you do not want to post the log publicly, you can mark the attachment as private.

Reply with quote

Advertisement

You can post new topics in this forum