Powershell:压缩按月分组的文件

时间:2014-04-26 12:18:18

标签: powershell

我使用以下脚本来压缩文件。

  
# 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
}

它工作正常,但它压缩每个单独的文件,我想知道我是否可以根据月份或周压缩文件。我在互联网上看到了这个选项group {"{0:MMM}{0:yyyy}" -f $_.CreationTime},但我不太确定如何将它与当前脚本集成。

我在powershell中直接执行了以下这一行并且它可以工作,但是当我尝试将它与上面的脚本集成时它不起作用,也许循环需要调整。

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

并且它工作正常,但是当涉及到压缩我不能让它工作

enter image description here

PS。我之后也会使用if ($LASTEXITCODE -eq 0) {Remove-Item $file}删除原始文件

1 个答案:

答案 0 :(得分:1)

您需要使用另一个foreach循环遍历新分组文件的集合。 将# filter files下方的行更改为以下内容:

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