Search code examples
powershellftpwinscpwinscp-net

How do I upload the last 3 files in a directory with WinSCP?


Trying to upload the last 3 files in a directory. I figured I can set the last 3 files and make them as an alias but I'm not sure how to do that..

Originally WinSCP was the transferring three specific file names, but it will change daily.

"put apple" `
"put pear" `
"put orange" `
& "C:\Program Files (x86)\WinSCP\WinSCP.com" `
  /log="C:\writable\path\to\log\WinSCP.log" /ini=nul `
  /command `
    "open ftp...." `
    "lcd C:\directorywithfiles" `
    "cd /" `
    # edit this to put the last 3 files
    $dir = "C:\directorywithfiles"
    $lastest = Get-ChildItem -Path "$path\*" -Exclude "*.php" -File | Sort-Object -Property LastWriteTime -Descending | Select-Object -First 3
    $latest.name

    #this section is what i'm trying to upload
    "put <$file1>" `
    "put <$file2>" `
    "put <$file3>" `

    "exit"

$winscpResult = $LastExitCode
if ($winscpResult -eq 0)
{
  Write-Host "Success"
}
else
{
  Write-Host "Error"
}

exit $winscpResult

Solution

  • First, you need to collect the names before your WinSCP commandline, not to break it. And then use syntax like $($lastest[0]) to refer to the found names:

    $dir = "C:\directorywithfiles"
    $lastest = Get-ChildItem -Path "$path\*" -Exclude "*.php" -File |
        Sort-Object -Property LastWriteTime -Descending | Select-Object -First 3
    
    & "C:\Program Files (x86)\WinSCP\WinSCP.com" `
      /log="C:\writable\path\to\log\WinSCP.log" /ini=nul `
      /command `
        "open ftp...." `
        "lcd $dir" `
        "cd /" `
        "put $($lastest[0])" `
        "put $($lastest[1])" `
        "put $($lastest[2])" `
        "exit"
    
    • Note that I'm reusing the $dir variable.
    • I'm not sure that the Select-Object -First 3 does anything useful. It can most likely be removed.