使用powershell和7zip创建存档的脚本
我们有几个服务器每天将日志文件写入C:\Logs。每个月都应该运行一个脚本来识别超过30天的文件,对它们进行归档,并删除源文件。C:\Logs文件夹包含日志文件,子文件夹(名为12344567890)也包含日志文件。作为Powershell的新手,我整合了下面的脚本,希望能够自动完成这项任务 该脚本能够识别超过30天的文件(我在测试它时让它输出文件名),但当归档例程启动时,它会将C:\Logs文件夹中的所有内容压缩,并且不会保留子文件夹结构 该脚本可能不是以最好的方式编写的,因此,如果您对我如何改进它并让它做它需要做的事情有任何建议,我希望听到任何建议使用powershell和7zip创建存档的脚本,powershell,Powershell,我们有几个服务器每天将日志文件写入C:\Logs。每个月都应该运行一个脚本来识别超过30天的文件,对它们进行归档,并删除源文件。C:\Logs文件夹包含日志文件,子文件夹(名为12344567890)也包含日志文件。作为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"
在阅读了更多内容并使用了这里发布的脚本和帮助之后,我想出了一些我需要它做的事情。我相信有更好的方法(比如添加更多的逻辑和if/then语句)但是已经足够好了。当我更擅长编写powershell脚本时,我可能会重新访问此脚本。这是我得到的
#========================================================
#
# 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 = 'youremail@mail.com'
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"
你必须使用7zip吗 我已经使用完成了相同的任务,并且能够保存文件夹结构 这是我的代码,您可以使用它并将日期逻辑添加到其中:
[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()
问题是您告诉7zip只压缩源目录中的
*.txt
文件(非递归)。相反,您需要将在var$files
中收集的文件列表传递给它。毕竟,你做了所有的工作,为什么不使用它呢?您可能还需要设置工作目录(-w
选项)。感谢更新的代码。我运行了它,这是我得到的错误:方法调用失败,因为[System.Object[]]不包含名为“Trim”的方法。在C:\Users\b012991\Desktop\semi_final.ps1:20 char:19+if($FileNames.Trim#hi@user1791716),很抱歉我没有测试完整的脚本。我已经做了更改
[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()