Question:
I want to compress multiple files into one zip.
I am stuck with this at the moment:
1 2 3 4 5 6 |
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:
1 2 |
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.
Answer:
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:
1 2 |
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:
1 2 |
dir C:\Logs | where { $_.Extension -eq ".txt" } | foreach { Write-Zip $_.FullName "$_.zip" } |
Related resources: