Search code examples
.netpowershellftpwinscpwinscp-net

Upload most recent file to FTP server using PowerShell ISE or WinSCP


I want to upload the recent XML file from my local folder into FTP server using PowerShell automation script. I searched through internet and found that it can be achieved through WinSCP in PowerShell. Anyone have any information how to achieve this using PowerShell ISE or WinSCP?

enter image description here

I want to upload ABCDEF.XML which has 10pm timestamp from my local folder to FTP server.


Solution

  • There's WinSCP example for your exact task: Upload the most recent file in PowerShell.

    The only modification you need to do is that the script is for SFTP, while you want FTP. Though the change is trivial and pretty obvious:

    try
    {
        # Load WinSCP .NET assembly
        Add-Type -Path "WinSCPnet.dll"
     
        # Setup session options
        $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
            Protocol = [WinSCP.Protocol]::Ftp
            HostName = "example.com"
            UserName = "user"
            Password = "mypassword"
        }
     
        $session = New-Object WinSCP.Session
     
        try
        {
            # Connect
            $session.Open($sessionOptions)
     
            $localPath = "c:\toupload"
            $remotePath = "/home/user"
     
            # Select the most recent file.
            # The !$_.PsIsContainer test excludes subdirectories.
            # With PowerShell 3.0, you can replace this with
            # Get-ChildItem -File switch 
            $latest =
                Get-ChildItem -Path $localPath |
                Where-Object {!$_.PsIsContainer} |
                Sort-Object LastWriteTime -Descending |
                Select-Object -First 1
     
            # Any file at all?
            if ($latest -eq $Null)
            {
                Write-Host "No file found"
                exit 1
            }
     
            # Upload the selected file
            $session.PutFiles(
                [WinSCP.RemotePath]::EscapeFileMask($latest.FullName),
                [WinSCP.RemotePath]::Combine($remotePath, "*")).Check()
        }
        finally
        {
            # Disconnect, clean up
            $session.Dispose()
        }
     
        exit 0
    }
    catch
    {
        Write-Host "Error: $($_.Exception.Message)"
        exit 1
    }
    

    If you find anything confusing about the code, you have to be more specific.


    Though easier is to use plain WinSCP script with its -latest switch from a plain Windows batch file (or PowerShell if you prefer).