使用PowerShell中的WinSCP .NET程序集将比X天新的日志/文件从Unix SFTP服务器复制到Windows

时间:2018-08-02 14:09:47

标签: windows powershell sftp winscp winscp-net

此代码使用WinSCP .NET程序集将文件从远程Unix服务器下载到Windows Server。但是,我只希望它复制过去30天的日志,而不是将所有日志文件从源Unix服务器上的logs文件夹复制到目标Windows服务器。原因是我不希望它填充目标Window Server上的C驱动器

param (
    $localPath = "d:\Logs\OnlineLogs",
    $remotePath = "/application/oracle",
    $fileName =  "int_access*.*"
)

try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"

    # Set up session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = ""
        UserName = ""
        Password = ""
        SshHostKeyFingerprint = ""
    }

    $session = New-Object WinSCP.Session 

    try
    {
        $session.Open($sessionOptions)

        $session.GetFiles(($remotePath + $fileName), ($localPath + $fileName)).Check()
    }
    finally
    {
        #Disconnect, clean up
        $session.Dispose()
    }

    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

1 个答案:

答案 0 :(得分:1)

您可以使用filemask with a time-constraint

$transferOptions = New-Object WinSCP.TransferOptions -Property @{
    FileMask = "*>=30D"
}

$session.GetFiles(
    (Join-Path $remotePath $fileName),
    [WinSCP.RemotePath]::CombinePaths($localPath, "*.*"),
    $False, $transferOptions).Check()

(您还缺少路径和文件名之间的斜杠和反斜杠,这就是为什么我添加了Join-PathCombinePaths调用的原因。)