user1791716
user1791716

Reputation: 51

Script to create archive using powershell and 7zip

We have several servers that write log files to C:\Logs on a daily basis. Every month, a script is supposed to run to identify files older than 30 days, archive them, and delete the source file. The C:\Logs folder contains log files, and sub folders (named 1234, 4567, 7890) that also contain log files. Being new to Powershell, I put together the script below in the hopes that I could automate this task.

The script is able to identify the files older than 30 days (I had it output the file names when I was testing it) but when the archive routine kicks off, it zips everything up in the C:\Logs folder and does not keep the sub folder structure.

The script is probably not written in the best way possible, so please, if you have any suggestions on how I can improve it and get it to do what it needs to, I would love to hear any suggestions.

$Hname = hostname #Name of server
$Source = "C:\logs" #Folder where log files reside
$Archive = "C:\logs\$hname\Archive.zip" #Folder where archive file will be created
$Extension = "*.txt" #Only files with this extension will be identified and archived
$Date = Get-Date #Today's date
$Days = "30" #Number of days past today's date that will be archived
$Files  =  get-childitem $Source  -include $Extension -recurse | Where-Object {$_.LastWriteTime -lt $Date.AddDays(-$Days)}                                                         
$FileNames = ""

foreach ($File in $Files)
{
    write-host "File Name : $File " $File.LastWriteTime 
    $FileNames = $FileNames + " " + $File  
}
write-host "Files to archive : " $FileNames

if($FileNames.Trim() -ne "")
{
    [string]$Zip = "C:\apps\7-zip\7z.exe"; #path to 7Zip executable
    [array]$arguments = "a", "-tzip", "-y", $Archive, $Source+$Extension;
    & $Zip $arguments ;
}

foreach ($File in $Files)
{
    write-host "Deleting file :"$File
    #remove-item $File -exclude *.zip
}
else
{
    write-host "No files to archive"
}

write-host "Archive Completed" 

Upvotes: 4

Views: 24793

Answers (3)

ProfessionalAmateur
ProfessionalAmateur

Reputation: 4563

Do you have to use 7zip?

I have done the same task using dotnetzip and was able to save the folder structure.

Here is my code, you can use this and add your date logic to it:

[System.Reflection.Assembly]::LoadFrom("c:\\\User\\bin\\Ionic.Zip.dll");
$zipfile = new-object Ionic.Zip.ZipFile("C:\user\temp\logs\TestZIP.zip");

$directory = "C:\user\temp\logs\"
$children = get-childitem -path $directory
foreach ($o in $children)
{
   if($o.Name.EndsWith(".log")){
      $e = $zipfile.AddFile($o.FullName)
   }
}
$zipfile.Save()
$zipfile.Dispose()

Upvotes: 2

user1791716
user1791716

Reputation: 51

After reading some more and using the scripts and assistance posted here, I came up with something that does what I need it to do. I'm sure there are better ways to go about it (like adding more logic and if/then statements) but it's good enough. I might revisit this script when I get better at scripting powershell. Here's what I got...

#========================================================
#
#           Log Archive & Move Script
#           Ver. 1.0.0  11/12/2012
#
#========================================================

#Machine hostname - needed for archive creation and identification
$hname = hostname

#Map network drive
$net = $(New-Object -Com WScript.Network)
$net.MapNetworkDrive("X:", "\\your network share\your folder",  
$false, "domain\user", "password") 

#Network folder where archive will be moved and stored
$newdir = "X:\your folder\$hname"

#Archive log entry
$log = "c:\logs\"+ $today + " " + $hname + " " + "Log Archive.txt"

#Local folder where archive file will be created
$archive = "C:\temp\"+ $today + " " + $hname + ".zip" 

#Path to network folder
$archpath = "$newdir" 

#Today's date
$Now = Get-Date 

#Today's date formatted for archive file creation
$today = Get-Date -f MM-yyyy 

#Files older than $Days will be archived and deleted
$Days = "45" 

#Folder where files you want archived are stored
$TargetFolder = "C:\Folder\Logs" 

#Only files with this extension will be archived and deleted
$Extension = "*.txt" 

$LastWrite = $Now.AddDays(-$Days)
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -   le "$LastWrite"}
$allfiles = "C:\temp\@()"

new-item $newdir -itemtype directory -force



#=================================================
#                        
#   -Identify log files older than x days
#   -Create zip archive
#   -List which files were archived
#   -Write log entry
#
#=================================================

foreach ($File in $Files)  
{ 

add-content -path $log -value "Archived: $file  to $archive  on $Now succesfully"

if ($File -ne $NULL)
    {

function create-7zip ([string] $TargetFolder){
#path to 7Zip executable
[string]$Zip = "C:\path to 7zip\7-zip\7z.exe"; 
[array]$args = "a", "-tzip", "-y", "-r", "$archive";

& $Zip $args $file;
}


    write-host "Archiving File $File" -ForegroundColor "Blue" 
    create-7zip | Out-File $allfiles
    }
else
    {
    Write-Host "No files to archive" -foregroundcolor "Red"
    }
}





#=================================================
#                       
#   -Delete files that were already archived
#   -Exclude newly created zip file
#   -List which files were deleted
#   -Write log entry
#
#=================================================     

foreach ($File in $Files)
{
write-host "Deleting file :"$File
remove-item $File -exclude *.zip
add-content -path $log -value "Deleted file:`t$file succesfully"
}




#======================================================
#                       
#   -Create folder in log archive repository
#   -Move zip archive to long term storage
#   -List files that were moved
#   -Write log entry
#
#====================================================== 

new-item $newdir -itemtype directory -force
try
{
Move-Item $archive -destination $archpath -force -ErrorAction:SilentlyContinue
"Moved $archive to $archpath at $now successfully   `r`n=================================================================================================    ========================================`r`n" | add-content $log
}
catch
{
"Error moving $archive:" | add-content $log
}
write-progress -activity "Moving Archive" -status "Progress:"


#=========================================================
#                       
#   -Email log to recepients with a brief explanation
#
#=========================================================

$Mail = @{
SMTPServer = '127.0.0.1'
Body = 'Log archive operations have completed on server:' + "  " + $hname + "  " + '@' + "  " +    $now  
To = '[email protected]'
From = $hname + '@mail.com'
Subject = $hname + " " + 'Log Archive Created'
 }
"c:\logs\"+ $today + " " + $hname + " " + "Log Archive.txt" | Send-MailMessage @Mail


#=========================================================
#                       
#   -Disconnect mapped network drive used to move archive
#
#=========================================================

$net.RemoveNetworkDrive("x:") 


#=========================================================
#                       
#   -Finish script
#
#=========================================================

write-host -foregroundcolor "Red" "`r`n Archive Completed. Email Sent" 

Upvotes: 1

Jackie
Jackie

Reputation: 2634

    $Hname = hostname #Name of server
    $Source = "C:\logs" #Folder where log files reside
    $Archive = "C:\logs\$hname\Archive.zip" #Folder where archive file will be created
    $Extension = "*.txt" #Only files with this extension will be identified and archived

    $Days = "30" #Number of days past today's date that will be archived
    $CutDay = [DateTime]::Now.AddDays($Days)
    $Files  =  get-childitem $Source  -include $Extension -recurse | Where-Object {$_.LastWriteTime -lt $CutDay}                                                         

    foreach ($File in $Files)
    {
        write-host "File Name : $File " $File.LastWriteTime 
    }

    pushd $Source
    $FileNames = @($Files | %{$_.FullName.Substring($Source.Length+1)} )

    if($FileNames.Count -ne 0)
    {
        [string]$Zip = "C:\apps\7-zip\7z.exe"; #path to 7Zip executable
        [array]$arguments = @("a", "-tzip", "-y", $Archive) + $FileNames
        & $Zip $arguments ;
    }

    foreach ($File in $Files)
    {
        write-host "Deleting file :"$File
        #remove-item $File -exclude *.zip
    }
    else
    {
        write-host "No files to archive"
    }

    write-host "Archive Completed" 

Upvotes: 3

Related Questions