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"
*.txtfiles found in your Source directory (non-recursive). Instead, you need to pass it the list of files that you collected in the var$Files. After all, you did all that work, why not use it? You may also need to set the work directory (-woption).