Powershell 脚本到 SFTP 新文件

Powershell 脚本到 SFTP 新文件

我这里有一个脚本,可以将文件从一个位置 SFTP 传输到另一个位置,该脚本运行良好,但我想更改该脚本,以便它只复制尚不存在的文件。我对 powershell 有点菜鸟,所以任何帮助都将不胜感激。

cd "c:\Program Files (x86)\WinSCP\" # location of .NET assembly ddl file

try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions
    $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
    $sessionOptions.HostName = "192.168.xxx.xxx"
    $sessionOptions.UserName = "xxxx"
    $sessionOptions.Password = "xxxx"
    $sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx"


    $session = New-Object WinSCP.Session

    try
    {
        # Connect
        $session.Open($sessionOptions)

        $stamp = Get-Date -f "yyyyMMdd"
        $fileName = "export_$stamp.txt"
        $remotePath = "/home/user/john/reports"
        $localPath = "\\fileserver\reports\"


        if ($session.FileExists($remotePath))
        {
            if (!(Test-Path $localPath))
            {
                Write-Host (
                    "File {0} exists, local backup {1} does not" -f
                    $remotePath, $localPath)
                $download = $True
            }


            if ($download)
            {
                # Download the file and throw on any error
                $session.GetFiles($remotePath, $localPath).Check()

                Write-Host "Download to backup done."
            }
        }
        else
        {
            Write-Host ("File {0} does not exist yet" -f $remotePath)
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

    exit 0
}
catch [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}

非常感谢。

答案1

从 WinSCP 示例中获取的脚本Session.GetFiles仅针对单个文件而设计。您尝试将其改为同步目录。这行不通。

要同步目录,请使用Session.SynchronizeDirectories

# Synchronize files
$synchronizationResult = $session.SynchronizeDirectories(
    [WinSCP.SynchronizationMode]::Local, $localPath $remotePath)

# Throw on any error
$synchronizationResult.Check()

相关内容