简体   繁体   中英

Powershell: Compress files grouped by month

I am using the following script to compress files.

# set folder path
$dump_path = "\\somepath\"

# set min age of files
$max_days = "-30"

# get the current date
$curr_date = Get-Date

# determine how far back we go based on current date
$zip_date = $curr_date.AddDays($max_days)

# filter files
$files = Get-ChildItem $dump_path | Where-Object { ($_.LastWriteTime -lt $zip_date) -and ($_.psIsContainer -eq $false) }

ForEach ($file in $files) {

    & "C:\Program Files\7-Zip\7z.exe" u -mx9 -t7z -m0=lzma2 ($file.FullName + ".7z") $file.FullName
}

It works fine, however, It compress each individual file, I was wondering if I could compress files based on the month or week. I saw this option group {"{0:MMM}{0:yyyy}" -f $_.CreationTime} on the internet but I am not quite sure how to integrate it with the current script.

I executed the following line straight in powershell and it works, but when I try to integrate it with the above script it doesn't work, maybe the loop needs tweaking.

Get-ChildItem C:\Users\mypath -filter "*psv.*" | group {"{0:MMMM} {0:yyyy}" -f $_.CreationTime} 

and it works fine, but when it comes to compressing i Cant get it to work

在此处输入图片说明

ps. I will also be using if ($LASTEXITCODE -eq 0) {Remove-Item $file} to delete original files afterwards

You need to iterate through the collection of newly grouped files with another foreach loop. Change lines below # filter files to the following:

$groups = Get-ChildItem $dump_path | 
    Where-Object { ($_.LastWriteTime -lt $zip_date) -and ($_.psIsContainer -eq $false) } | 
    group {"{0:MMMM} {0:yyyy}" -f $_.CreationTime}

ForEach ($group in $groups) {
    ForEach($file in $group.Group){
        & "C:\Program Files\7-Zip\7z.exe" u -mx9 -t7z -m0=lzma2 ($group.Name + ".7z") $file.FullName
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM