Solved: Only download files older than 2 minutes

Advertisement

phoeneous
Joined:
Posts:
2

Solved: Only download files older than 2 minutes

Hello. I'm trying to setup a powershell script that will only download files that are older than the current time minus two minutes. When I run the script below it grabs all files regardless of their .LastWriteTime. Any help is appreciated.

This is just a snippet, not the full code.

param (
    $localPath = "C:\Download\",
    $remoteDir = "/remote/path/",
    $remotePath = "/remote/path/*.xml"
)

try
    {
        Write-Host "Trying connection..."
        $session.Open($sessionOptions)
        $earlier = (Get-Date).AddMinutes(-2)
        $directory = $session.ListDirectory($remoteDir)

        foreach ($fileInfo in $directory.Files)
        {
            if ($fileInfo.LastWriteTime -lt $earlier)
            {
                Write-Host $fileInfo.Name " will be downloaded"
                $transferResult = $session.GetFiles($remotePath, $localPath)
                foreach ($transfer in $transferResult.Transfers)
                {
                    if ($transfer.Error -eq $Null)
                    {
                    Write-Host "Download of $($transfer.FileName) succeeded."
                    }
                    else
                    {
                    Write-Host "Download of $($transfer.FileName) failed: $($transfer.Error.Message)"
                    }
                }              
             }
         }        
    }
Last edited by phoeneous on 2019-02-25 18:16; edited 1 time in total

Reply with quote

Advertisement

phoeneous
Joined:
Posts:
2

Solved

Was able to achieve my results using this method:

$session.Open($sessionOptions)
        $directory = $session.ListDirectory($remoteDir)
        $filesToDownload = $session.EnumerateRemoteFiles($remoteDir, $Null, [WinSCP.EnumerationOptions]::AllDirectories) | Where-Object { $_.LastWriteTime -lt $earlier }

        foreach ($fileToDownload in $filesToDownload)
        {
            $sourcePath = [WinSCP.RemotePath]::EscapeFileMask($fileToDownload.FullName)
            $transferResult = $session.GetFiles($sourcePath, $localPath)
            if ($transferResult.IsSuccess)
            {
                foreach ($transfer in $transferResult.Transfers)
                {
                    Write-Host "Succesfully downloaded $($transfer.FileName)..."
                }
            }
            else
            {
                Write-Host "Failure downloading $($transferResult.Failures[0].Message)..."
            }            
        }

Reply with quote

Advertisement

You can post new topics in this forum