PowerShell SFTP backup to remote NAS/Server

Advertisement

iulian07
Guest

PowerShell SFTP backup to remote NAS/Server

I am a beginner to PowerShell but I adapted a few scripts, that I found and this script should take every file in a local directory and make a backup on a remote NAS/server. It will take the last file by date, transfer it, count the number of files on the remote nas/server and if the number of files is > than x (cleanup), will delete the oldest file else will keep all files. I don't know, if this is the easiest way and best solution, but it's functional.

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
35,731
Location:
Prague, Czechia

Re: Powershell Sftp Backup to remote NAS/Server

Thanks for sharing your solution. Looks good. You just unnecessarily list the remote directory twice.

Do something like this instead:
$directoryInfo = $session.ListDirectory($RemotePath)
 
if ($directoryInfo.Files.Count -ge 10)
{
    $latest1 =
        $directoryInfo.Files |
        Where-Object { -Not $_.IsDirectory } |
        Sort-Object LastWriteTime -Descending |
        Select-Object -last 1
    $session.RemoveFile($latest1.FullName).Check()
}

Reply with quote

iulian07
Guest

Re: Powershell Sftp Backup to remote NAS/Server

Hi Martin,
I didn't manage to implement your solution, but I did saw that in my script is a mistake, this line #$x= $files.length should be active. The greatest problem that I had is the counting of files by the remote server, when this line is executed:
$files = $session.EnumerateRemoteFiles($remotePath, $null, [WinSCP.EnumerationOptions]::None).count
It just gives me back a string of 1s, so for every file (ex.5 files) I get back a string like this 1 1 1 1 1, that's why i needed to count with this line $x= $files.length how many characters are in the string. It's a workaround, not the prettiest but works.

Reply with quote

Advertisement

You can post new topics in this forum