Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress multiple files into one zip with PowerShell?

I want to compress multiple files into one zip.

I am stuck with this at the moment:

Get-ChildItem -path C:\logs -Recurse | Where {$_.Extension -eq ".csv" -and $_.LastWriteTime -lt (Get-Date).AddDays(-7)} | write-zip -level 9 -append ($_.LastWriteTime).zip | move-item -Force -Destination {
    $dir = "C:\backup\archive"
    $null = mkdir $dir -Force
    "$dir\"
}

I get this exception

Write-Zip : Cannot bind argument to parameter 'Path' because it is null.

This part is the problem:

write-zip -level 9 -append ($_.LastWriteTime).zip

I have never used powershell before but i have to provide a script, I can't provide a c# solution.

like image 646
mrt181 Avatar asked Apr 12 '11 12:04

mrt181


People also ask

How do I zip a lot of files at once?

Right-click on the file or folder. To place multiple files into a zip folder, select all of the files while hitting the Ctrl button. Then, right-click on one of the files, move your cursor over the “Send to” option and select “Compressed (zipped) folder”.

How do I zip a file in PowerShell script?

Compress-Archive uses the Path parameter to specify the root directory, C:\Reference with an asterisk ( * ) wildcard. The DestinationPath parameter specifies the location for the archive file. The Draft. zip archive contains the root directory's files and subdirectories.

What is the fastest way to zip large files?

To zip (compress) a file or folderPress and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.


1 Answers

The problem is that Get-ChildItem returns instances of the System.IO.FileInfo class, which doesn't have a property named Path. Therefore the value cannot be automatically mapped to the Path parameter of the Write-Zip cmdlet through piping.

You'll have to use the ForEach-Object cmdlet to zip the files using the System.IO.FileInfo.FullName property, which contains the full path:

Get-ChildItem -Path C:\Logs | Where-Object { $_.Extension -eq ".txt" } | ForEach-Object { Write-Zip -Path $_.FullName -OutputPath "$_.zip" }

Here's a shorter version of the command using aliases and positional parameters:

dir C:\Logs | where { $_.Extension -eq ".txt" } | foreach { Write-Zip $_.FullName "$_.zip" }

Related resources:

  • Cool Pipeline Tricks, Redux (TechNet Magazine)
like image 131
Enrico Campidoglio Avatar answered Sep 28 '22 19:09

Enrico Campidoglio