简体   繁体   中英

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 ac# solution.

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:

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