Download only new files with WinSCP in PowerShell

假装没事ソ 提交于 2020-06-12 12:15:05

问题


How could I download the latest files, or files that were posted a certain amount of days? Importing a CSV file that contains a Source and a Destination column. Needs to check, if the path exists/file exists and only download new files.

Script right now is moving all the files to the correspondent folder - but once I run the script again, its not downloading only new files.

Here's an example of the CSV file:

try{

  Add-Type -Path "WinSCPnet.dll"
  # Setup session options
  $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::sftp
    HostName = "xxxxx"
    UserName = "xxxxr"
    Password = "xxxxxxx"
    PortNumber = "xx"
    GiveUpSecurityAndAcceptAnySshHostKey = $true
  }

  $session = New-Object WinSCP.Session

  try{
    # Connect
    $session.Open($sessionOptions)
    # Download files
    $transferOptions = New-Object WinSCP.TransferOptions
    $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

    Import-Csv -Path "C:\movefiles.csv" -ErrorAction Stop | foreach{

      Write-Host $_.Source
      Write-host $_.Destination 

      $transferResult =
        $session.GetFiles($_.Source, $_.Destination, $False, $transferOptions)

      # Throw on any error
      $transferResult.Check()

      # Print results
      $smtpBody = ""
      foreach ($transfer in $transferResult.Transfers){

        Write-Host "Download of $($transfer.FileName) succeeded"

        $smtpbody += " Files : ( $transfer.filename - join ', ')" +
                     " Current location: $($_.Destination) "
      } 

      Send-Mail Message @smtpMessage  -Body $smtpbody
    }
    finally {
      # Disconnect, clean up
      $session.Dispose()
    }
  }
  catch
  {
    Write-Host "Error: $($_.Exception.Message)"
  }
}

Example of the CSV file:

Source, Destination
/client1/Business/2019, C:\test\test1
/client2/Reporting/2018, C:\test\test2

回答1:


If your Source and Destination are plain directory paths, you can simply replace Session.GetFiles with Session.SynchronizeDirectories:

Import-Csv -Path "C:\movefiles.csv" -ErrorAction Stop | foreach {

    $synchronizationResult = $session.SynchronizeDirectories(
        [WinSCP.SynchronizationMode]::Local, $_.Destination, $_.Source, $False)

    $synchronizationResult.Check()

    foreach ($download in $synchronizationResult.Downloads)
    {
        Write-Host "File $($download.FileName) downloaded"
    }
}

See also WinSCP FAQ How do I transfer new/modified files only?



来源:https://stackoverflow.com/questions/59726516/download-only-new-files-with-winscp-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!