3

我们有几台服务器每天将日志文件写入 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" 
4

3 回答 3

2
    $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" 
于 2012-11-02T03:20:29.460 回答
1

你必须使用7zip吗?

我使用dotnetzip完成了相同的任务,并且能够保存文件夹结构。

这是我的代码,您可以使用它并向其中添加日期逻辑:

[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()
于 2013-09-06T19:34:53.787 回答
0

在阅读了更多内容并使用了此处发布的脚本和帮助之后,我想出了一些可以满足我需要的东西。我确信有更好的方法来解决它(比如添加更多逻辑和 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" 
于 2012-11-13T17:03:10.163 回答