需求
在我们的实验环境,每天生成大量txt格式文件,且硬盘空间特别紧张,需要定期清理日志,释放大量空间。

实现工具
Windows2008计划任务    
POWERSHELL脚本    
压缩软件

功能
每天定时执行脚本,将指定目录下的按照目录进行备份

配置
脚本
#需要压缩的天数前的日志    
$DayNumber = "-58"    
#压缩到的目录    
$RarPath = "D:\log\bak"    
#被压缩文件的目录    
$LogPath = "D:\LOG"    
#软件winrar路径    
$WinRarPath = "C:\Program Files\WinRAR\WinRAR.exe"


cd C:\TOOLS\rarlog    
$logDate1 = (Get-Date).AddDays($DayNumber)    
$logDate = (Get-Date).AddDays($DayNumber - 1)    
Get-Date | out-file  log.txt -append    
if ( test-path $LogPath ) {    
$logFiles = Get-ChildItem -Path $LogPath -Recurse -INCLUDE *.txt  |Where-Object -FilterScript {($_.LastWriteTime -gt $logDate) -and ($_.LastWriteTime -lt $logDate1) }|select fullname,Directory,name,basename,Directoryname    
$DevicePath = $LogPath.Substring(0,2)    
$DeviceFreeSpace = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID = '$DevicePath'" | select -ExpandProperty FreeSpace    
if ( $DeviceFreeSpace -lt "1000000000" ) {    
   "磁盘空间严重不足" | out-file  log.txt -append    
   exit    
}    
if ( !($logFiles)) {    
   "指定时间段没有发现txt文件" | out-file  log.txt -append    
   exit    
}    
foreach ($File in $logFiles)    
{    
   $tmp = $file.DirectoryName    
   $tmp = $tmp.Substring(0,2)    
   Write-Host $tmp  
   $RarFile = $file.DirectoryName.Replace($tmp, $RarPath)    
   Write-Host $RarFile    
   if ( !(test-path $RarFile) ) { New-Item $RarFile -type directory }    
    $RarPathFile = $RarFile + "\" +$file.basename    
   Write-Host $RarPathFile  
   $RarPathFile | out-file  log.txt -append    
   cmd /c $WinRarPath  a –df -y $RarPathFile $file.fullname    
}    
} else { "备份目录不存在" | out-file  log.txt -append }


计划任务
SCHTASKS /Create /SC DAILY /ST 05:00 /TN GLSVRLOGRAR /TR "POWERSHELL.EXE -FILE C:\TOOLS\rarlog\rarlog.ps1"  /RL HIGHEST  /RU backupuser /RP "********"


说明
1.我们用的压缩软件winrar,有几个参数说明    
-df:压缩完成后删除源文件    
-y:假设对全部询问都回答是,主要针对,有的文本文件被人占用,无法压缩,会弹出中断的文本框让你选择    
2.关于脚本几点注意,也就是脚本中的几个IF    
A.需要备份的路径不存在,winrar会将当前目录进行压缩,这是非常可怕的,首先默认路径是“C:\Windows\system32”,所在脚本第一条就是把默认路径改成脚本所在目录,另外还是加了if判断。    
B.防止所在磁盘空间不足,会导致winrar无法进行压缩,所以增加了IF,开始没有这个判断,导致文件没有压缩或者压缩没有保存下来,就删除源文件    
C.如果被压缩的路径存在,而没有符合txt文件,也会出现压缩当前目录,所以又增加一个IF,还是安全重要    
3.POWERSHELL的日期计算AddDays,居然支持小数,可以实现半天或者几小时前的压缩