繁体   English   中英

使用 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
}

如果您发现代码有任何令人困惑的地方,则必须更加具体。


尽管使用普通 WinSCP 脚本及其-latest开关从普通 Windows 批处理文件(如果您愿意,也可以使用 PowerShell)更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM