Downloading newest file and deleting older files scripting

Advertisement

Hansschulte
Joined:
Posts:
1
Location:
Eygelshoven

Downloading newest file and deleting older files scripting

Good evening,
new member here.
I have a question;
My weather-camera is uploading every hour a new .jpg file to my FTP server. My directory is filling up with a lot of files. I want a script for Powershell to send the latest file to my local PC directory and the old files been deleted from the ftp server.
I found a script that is partially solving the problem.
It does NOT (yet):
- delete the files older then 2 hours ago.
- download the newest file.
What can I do? I do not find a solution.
Who can help me?
Here is the working script so far. Martin wrote it in 2016.Thanks in advance

# Load WinSCP .NET assembly
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
 
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "xxxxxx"
    UserName = "xxxxxx"
    Password = "xxxxxx"
}
 
try
{
    # Connect
    $session = New-Object WinSCP.Session
    $session.Open($sessionOptions)
 
    # List files
    $remotePath = "/public_html/Weercam/FI9853EP_00626EA2E6A9/snap"
    $directoryInfo = $session.ListDirectory($remotePath)
 
    # Find old files
    $limit = (Get-Date).AddDays(-1)
 
    $oldFiles =
        $directoryInfo.Files |
        Where-Object { -Not $_.IsDirectory } | 
        Where-Object { $_.LastWriteTime -lt $limit }
 
    # Delete them
    foreach ($oldFileInfo in $oldFiles)
    {
        $oldFilePath =
            [WinSCP.RemotePath]::EscapeFileMask($remotePath + "/" + $oldFileInfo.Name)
        $session.RemoveFiles($oldFilePath).Check()
    } 
 
    Write-Host "Done"
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}

Reply with quote

Advertisement

Advertisement

You can post new topics in this forum