Search code examples
powershellpowershell-2.0windows-server-2008-r2powershell-3.0powershell-1.0

Powershell: Compress files


I need to compress files based on the month and year they were written.

# group files based on extension month/year
$groups = Get-ChildItem C:\Users\mypath -filter "*psv.*" | Group-Object {"{0:MMMM} {0:yyyy}" -f $_.LastWriteTime }

# compress groups
ForEach ($group in $groups) {
    & "C:\Program Files\7-Zip\7z.exe" u ($group.FullName + ".7z") $group.FullName
}

The script above isn't working, however, When I run the following line alone

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

I get the following result which is fine. result

However, it isn't zipping the group of files.


Solution

  • Try this:

    $groups = Get-ChildItem C:\Users\mypath *psv.* | Group {"{0:MMMM}-{0:yyyy}" -f $_.LastWriteTime}
    foreach ($group in $groups) { 
        foreach ($file in $group.Group.FullName) { 
             Write-Host "Processing " + $group.Name + " " + $file 
             & "C:\Program Files\7-Zip\7z.exe" u ($group.Name + ".7z") $file
        } 
    }
    

    The Group property of the GroupInfo object output by GroupInfo contains all the files that are in that grouping. You have to enumerate those files.