Search code examples
.netpowershellsftpwinscpwinscp-net

Upload whole drive to a server using WinSCP in PowerShell skipping all files and folders that cannot be read


I'm trying to copy an entire drive for example D: drive files from a Windows box to a Linux box using PowerShell and WinSCPnet.dll. When I try copying particular folders, I am able to copy all the files from that folder to the Linux path. But when I try to copying the entire D: drive to a Linux box folder, I am getting the following error.

Error retrieving file list for "d:\$RECYCLE.BIN\S-1-5-21-1458064458-1966517317-3155185246-1003*.*". System Error. Code: 5.

$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
$transferResult = $session.PutFiles("d:\*", "/tmp/some/", $False, $transferOptions)
# Throw on any error
$transferResult.Check()

Expected result should be that it should copy the entire D drive to the destination Linux box folder, but the above mentioned error is coming.


Solution

  • You can make WinSCP .NET assembly skip all files and folders that cannot be opened by handling Session.QueryReceived event:

    # Continue on any error
    $session.add_QueryReceived( { 
        Write-Host "Error: $($_.Message)"
        $_.Continue()
    } )
     
    $session.PutFiles("d:\*", "/tmp/some/").Check()
    

    Code based on article Recursively download directory tree with custom error handling.


    Another option is to explicitly exclude the problematic files and folders from the transfer using TransferOptions.FileMask.