Monday, October 11, 2010

Powershell script that uses 7-zip to compress all files in a parameterizable folder

Powershell script that uses 7-zip to compress all files in a parameterizable folder that match the file pattern provided by the user.Any file that has not been modified in more than a particular time will be compressed. The compressed archive should be verified using the command-line compression tool. Once the compressed archive is validated, then the original file should be deleted. All arguments should be passed to the script at the command-line.
(Please not that this script has not been fully tested and can really be harmful for the system, try it at your own risk :D)

Param
($SourcePath = $(Read-host "Please enter the source directory path e.g. d:\data\")),
($TargetPath = $(Read-host "Please enter the target path e.g. d:\all\archive.zip")),
($Days = $(Read-Host "Files older than days?")),
($Pattern = $(Read-Host "Enter file pattern, e.g. *.txt"))
$CurrentDate = Get-Date
$LimitDate = $CurrentDate.AddDays(-$Days)
$Files  =  get-childitem $SourcePath  -include $Pattern -recurse | where {$_.LastWriteTime -le $LimitDate}
$FileNames = ""
foreach ($File in $Files)
{
write-host "File Name : $File " $File.LastWriteTime
$FileNames = $FileNames + " " + $File 
}
write-host "Files to compress : " $FileNames
if($FileNames.Trim() -ne "")
{
powershell  "&'c:\program files\7-zip\7z'" a $TargetPath   $SourcePath+$Pattern
#powershell.exe  "&'c:\program files\7-zip\7z'" t $TargetPath *.* -r
        foreach ($File in $Files)
 {
 write-host "Deleting file :"$File
 remove-item $File
 }
}
else
{
write-host "No files to compress"
}

write-host "Operation successful!"

No comments:

Post a Comment