我们有几台服务器每天将日志文件写入 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"
$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"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)