locked
Powershell Script to Zip\Compress Files Older Than Certain Days RRS feed

  • Question

  • I need a Powershell Script to do the following:

    1) Take a file of type XXX that is more than X days old than the current date, zip\compress and remove the files that were zipped leaving the zip files in the same directory.  

    2) Name the new zip with current month and year: MM_YR

    Currently, this script is creating by day instead of month

    $path = "C:\logs\"
    # Optional filter to only touch files with specified extension 
    $mask = "*.xml" 
    $ZipFileName= "_Backup.zip"
    #Filter to only touch files older than specified 
    $days = 30
    $problem = $false
    $date = (Get-Date).tostring("yyyyMMdd")
    $errorMessage="no issue"
     
     
    
     
    try {
        # Get all items from specified path, recursing into directories but not returning directories themselves. Excluding files with modificiation dates less than $days
        $files = Get-ChildItem $path -Recurse -Include $mask | where {($_.LastWriteTime -lt (Get-Date).AddDays(-$days)) -and ($_.psIsContainer -eq $false)} 
        foreach ($file in $files) {
            $Directory = $path + $file.LastWriteTime.Date.ToString('yyyy_MM_dd')
            if (!(Test-Path $Directory)) {
             New-Item $directory -type directory
         }
         Move-Item $file.fullname $Directory
        }
        $folders = Get-ChildItem $path -Directory  | % { $_.FullName }
        foreach ($folder in $folders) {
            $zipname = $folder + $ZipFileName
            if (!(test-path $zipname)){
            compress-archive -LiteralPath $folder -DestinationPath $zipname
            }
            if (test-path $zipname){
            remove-item -Recurse $folder 
            }
            else {
            Write-host $zipname + "Hello" + $folder
            }
        }
    }
    catch {
        $problem = $true
        $errormessage = $_.Exception.Message

    • Edited by MuhammadMBA Tuesday, August 8, 2017 12:51 AM
    Monday, August 7, 2017 10:42 PM

Answers

All replies