Need recursive zip script to zip parent folder and items more than 7 days old

Yeah it’s naming the ZIP file with the name of the parent dir that’s the issue.

My current script finds all the files in the folders older than 7 days and then spits them out as one zip file for each txt file, named the same as the txt file which is useless unless you can trace them back to the IIS worker process they came from (the name of the W3C folder is crucial for this in a multi-tenanted IIS environment) so this is the hurdle I’m currently facing.

Hi Sam,

How is this?

function New-LogZip {
    [CmdletBinding()]
    param (
        # Root path of logs
        [Parameter(Mandatory = $true)]
        [string]
        $Path,

        [Parameter(Mandatory = $true)]
        [string]
        $Destination
    )

    # Find logs over 7 days old
    $Logs = Get-ChildItem -Path $Path -File -Recurse | Where-Object {
        $_.LastWriteTimeUtc -lt [DateTime]::UtcNow.AddDays(-7)
    }
    # Cache parent and paths
    $ParentFolder = @{}
    $Logs | ForEach-Object {
        $ParentName = $_.Directory.Name
        Write-Verbose $ParentName
        if(-not $ParentFolder.ContainsKey($ParentName)){
            $ParentFolder[$ParentName] = @($_.FullName)
        }
        else {
            $ParentFolder[$ParentName] += $_.FullName
        }
    }

    $WorkingPath = Join-Path -Path $env:TEMP -ChildPath (New-Guid).Guid
    New-Item -Path $WorkingPath -ItemType Directory -ErrorAction Stop | Out-Null

    try {
        # Create temp location with parent
        $ParentFolder.GetEnumerator() | ForEach-Object {
            $NewPath = Join-Path -Path $WorkingPath -ChildPath $_.Key
            New-Item -Path $NewPath -ItemType Directory | Out-Null
            $_.Value | ForEach-Object {
                Copy-Item -Path $_ -Destination $NewPath
            }

            # Archive parentfolder
            $ZipLocation = Join-Path -Path $Destination -ChildPath "$($_.Key).zip"
            Compress-Archive -Path $NewPath -DestinationPath $ZipLocation -ErrorAction Stop
            Get-Item -Path $ZipLocation
        }

    } finally {
        Remove-Item -Path $WorkingPath -Recurse -Force
    }
}

We have a winner (I think!)

Ran this against a small chunk of log files and it seemed to work.
Now I’ve aimed it at the entire LogFiles dir and it’s chomping through them currently.

I’ll let you know if it fails.

Thanks Max!