我们有几台服务器每天将日志文件写入 C:\Logs。每个月,应该运行一个脚本来识别超过 30 天的文件,将它们存档,并删除源文件。C:\Logs 文件夹包含日志文件,以及还包含日志文件的子文件夹(名为 1234、4567、7890)。作为 Powershell 的新手,我将下面的脚本放在一起,希望可以自动执行此任务。
该脚本能够识别超过 30 天的文件(我在测试它时让它输出了文件名)但是当存档例程开始时,它会将所有内容压缩到 C:\Logs 文件夹中并且不保留子文件夹结构。
该脚本可能不是以最好的方式编写的,所以如果您对我如何改进它并让它做它需要做的事情有任何建议,我很想听听任何建议。
$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"