Script to create archive using powershell and 7zip

前端 未结 3 1975
天命终不由人
天命终不由人 2021-01-21 09:15

We have several servers that write log files to C:\\Logs on a daily basis. Every month, a script is supposed to run to identify files older than 30 days, archive them, and delet

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-21 09:38

        $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" 
    

提交回复
热议问题