Skip to content

Backup files with Powershell

April 19, 2012

Finally I found some good use for Powershell. I was always intrigued by Powershell when I read about it on Hanselman’s blog, but so far never really found a good use for it. But now that I am managing a webserver on which ascii files are stored regularly (complicated story  ;)), I needed some easy way to backup these files once they’re older than say 30 days. Things start clugging up fast !

So here it is, my first powershell script, it uses 7zip to put the files into an archive and subsequently removes them. Probably could see some improvement, but it’s working fine as it is now.

$ftp_root = "D:\Data\Ftp"
[string]$zipexe = "C:\7Zip\7z.exe"
$date = Get-Date 
$DateStr = '{0:yyyyMMdd}' -f $date

#start-transcript $(%{'d:\logs\archivelog_{0}.txt' -f $DateStr})
Write-Host "Archive script Datum : " $DateStr

foreach ($dir in (Get-ChildItem $ftp_root -Recurse | where {$_.PsIsContainer})) {
	 foreach($file in ($dir.GetFiles("P*.*") | where-object {$_.LastWriteTime -lt (get-date).AddDays(-30) } )) {	 

	Write-Host "Executing : $zipexe a -t7z " $(%{'{0}\{1} {2}' -f $dir.FullName, "archive.7z", $file.FullName})
	& $zipexe a -t7z $($dir.FullName + "\archive_" + $DateStr + ".7z") $file.FullName
        remove-item $file.FullName -force -whatif   
	 foreach($file in ($dir.GetFiles("J*.*") | where-object {$_.LastWriteTime -lt (get-date).AddDays(-30) } )) {	 
		& C:\7Zip\7z.exe a -t7z $($dir.FullName + "\archive_" + $DateStr + ".7z") $file.FullName

Comments are closed.

%d bloggers like this: