Post a reply

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)


Topic review


Re: [Powershell] Try to push some files via SFTP/WinSCP and handle all exceptions

It does not look like the server is shut down.

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.

Try to push some files via SFTP/WinSCP and handle all exceptions in PowerShell


I am scripting an automation copy via SFTP/WinSCP.

It's working fine, but I would like to have an issue if the SFTP server doesn't connect for example.

Currently, I add this condition in my script :
# Create a WinSCP session
$session = New-Object WinSCP.Session
# Upload files
$transferResult = $session.PutFiles("E:\DATA\test\Data\To process\*", $SSH_destination_path)
# Throw on any error
$result = $transferResult | ConvertTo-Json
echo $result
# Print results
foreach ($transfer in $transferResult.Transfers) {
    $Date = Get-Date -format G
    # Success or error?
    if ($transfer.Error -eq $Null) {
        $Log += ("{0} - Upload of {1} succeeded on the SFTP server {2}`n" -f $Date, $transfer.FileName, $SSH_hostname)
        # Upload succeeded, move source file to backup
        #Move-Item $transfer.FileName $archive_data_path
    } else {
        $ExceptionFlag = $true
        $Log += ("{0} - Upload of {1} failed: {2}`n" -f $Date, $transfer.FileName, $transfer.Error.Message)

If the SFTP server is on, all my files are uploaded.
But I would like to have an exception if the SFTP server can't connect, and my script doesn't do that for the moment.

I was thinking receive an issue with $transfer.Error.
But there is no issue at all, like all files will be copied, but it's not the case.

Here is the result of $transferResult in JSON:
                          "Destination""/lala - Copy.xml",
                          "FileName""E:\\DATA\\test\\Data\\To process\\lala - Copy.xml",
                          "FileName""E:\\DATA\\test\\Data\\To process\\lala.xml",

As you can see, there is a null for Error...
But the SFTP server is shutdown, so why I don't have any error here ?