使用 PowerShell ISE 或 WinSCP 将最新文件上传到 FTP 服务器

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

我想使用 PowerShell 自动化脚本将最近的 XML 文件从我的本地文件夹上传到 FTP 服务器。我在网上搜索了一下,发现可以通过PowerShell中的WinSCP来实现。有人知道如何使用 PowerShell ISE 或 WinSCP 实现此目的吗?

我想将具有晚上 10 点时间戳的 ABCDEF.XML 从我的本地文件夹上传到 FTP 服务器。

有适合您的确切任务的 WinSCP 示例:Upload the most recent file in PowerShell

您唯一需要做的修改是脚本是针对 SFTP,而您想要 FTP。尽管变化微不足道且非常明显:

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
}

如果您发现代码有任何混淆之处,您必须更加具体。


虽然更容易从普通 Windows 批处理文件(或 PowerShell,如果您愿意)使用 plain WinSCP script with its -latest switch