How to zip individual files in powershell

4.3k views Asked by At

I have a script that takes files and zips them into a bundle depending on the date. How would I zip up the files individually (perhaps foreach) and have them stay in that same directory? I also get an error on $FileSet2.

Function Zip
{
    Param
    (
        [string]$FileZip
        ,
        [string[]]$NeedsZipping
    )

    $Directory = Get-Location
    Set-Location "C:\Users\lostd\Desktop\7-ZipPortable\"
    .\7zG.exe A -tzip $FileZip $NeedsZipping | Out-Null
    Set-Location $Directory
}

$filename = "tester"
$CurrentTime = Get-Date
$DaySet1 = "5"
$DaySet2 = "10"
$TargetFolder = "C:\Users\lostd\Documents\*.*"
$LastMod = $CurrentTime.AddDays(-$DaySet1)
$LastMod2 = $CurrentTime.AddDays(-$DaySet2)
$FileSet1 = Get-Childitem $TargetFolder -Recurse | Where {$_.LastMod -lt "$LastMod2"}
$FileSet2 = Get-Childitem $TargetFolder -Recurse | Where {$_.LastMod -gt $LastWrite -AND $_.LastMod -lt $LastMod2}  
#$FileSet1

Zip C:\Users\lostd\Desktop\TEST.zip $FileSet1

If(Test-Path C:\Users\lostd\Desktop\TEST.zip)
{
    Remove-Item $FileSet2
}

Thanks in advance

2

There are 2 answers

0
Ben Scotch On BEST ANSWER

Ok, it took some time, but I got it figured out. There were a few issues. You will need to replace the following:

Zip C:\Users\skochkr\Desktop\TEST.zip $Files
If(Test-Path C:\Users\lostd\Desktop\TEST.zip)
    {Remove-Item $Files2}

with

foreach ($File in $Files)
{
    Set-Location "C:\Users\lostd\Documents\purge\"
    $Zipname = $File.Name.Replace(".", "-")
    Zip C:\Users\lostd\Documents\purge\$zipname $File
}
sleep 5   
foreach ($File in $Files)
{
    Remove-Item -Force $File
}

This will zip each file in $Files individually (instead of making one zip file with all the contents inside) whilst it keeps the same name and extension type. The destination of the zipped file also needed to be set to the desired location, otherwise the zipped file was sent to the folder where 7-Zip is located.

1
HAL9256 On

The error on $Files2 is that your lt/gt is flipped the wrong way around.

You are saying Where LastWriteTime is older (greater) than 10 days ago, AND less than 20 days ago, which is always false. I believe you want to flip the two around so that you get files where LastWriteTime is less than 10 days ago, yet older (greater) than 20 days ago.

As for bundling them, can you provide more information/clarification on how you want to bundle them, and where the files should go?