Powershell: compress backups and FTP transfer

I use this snippet to check my database backups folder for backup files not compressed yet, compress them using 7-Zip, and finally deleting the “*.bak” files to save some disk space. Notice files are ordered by lenght (smallest to biggest) before compression to avoid some files not being compressed.

$bkdir = "E:\BackupsPWS" #backups location directory
$7Zip = 'C:\"Program Files"\7-Zip\7z.exe' #compression utility
$files_to_transfer = New-Object System.Collections.ArrayList #list of zipped files to be transferred over FTP
$ftp_uri="myftpserver"
$user="myftpusername"
$pass="myftppassword"

#find .bak files not zipped yet, zip them, add them to the list to be transferrd
get-childitem -path $bkdir | Sort-Object length |
where { $_.extension -match ".(bak)" -and
-not (test-path ($_.fullname -replace "(bak)", "7z")) } |
foreach {
$zipfilename = ($_.fullname -replace "bak", "7z")
Invoke-Expression "$7Zip a $zipfilename $($_.FullName)"
$files_to_transfer.Add($zipfilename)
}

#find .bak files, if they've been zipped, delete the .bak file
get-childitem -path $bkdir |
where { $_.extension -match ".(bak)" -and
(test-path ($_.fullname -replace "(bak)", "7z")) } |
foreach { del $_.fullname }

#transfer each zipped file over FTP
foreach ($file in $files_to_transfer)
{
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) # FTP credentials
$ftp_urix = $ftp_uri + "/" + $file.Substring($bkdir.Length + 1) # ftp address where to transfer the file
$uri=[system.URI] $ftp_urix
$webclient.UploadFile($uri, $file) #transfer the file
}

2 responses to this post.

  1. There are tons of “awesome” searching soccer moves that
    a player can learn with follow. The most crucial factor to preserve in
    thoughts when finding out new moves is to be affected person, and not to rush.
    Exercise the moves little by little on your possess at initial, and after you get the cling of them do
    them at a lot quicker speeds till you truly feel ready to use them in practice or a sport.
    Every single participant has a distinct ability level and learning curve when it comes to soccer moves, so go at
    your possess speed and do not drive anything.

    Responder

  2. Posted by Rajasekhar on 24 abril, 2015 at 1:23

    Hi Can you post a code to download a text file from SFTP using powershell. We don’t want to use Winscp or any third party softwares.

    Responder

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: