I have the following script for zipping old files:
# Zipping old files and sending them to a file on desktop if older than 60 days
Function Zip {
Param(
[Parameter(Mandatory)]
[string]$zipFile
,
[Parameter(Mandatory)]
[String[]]$toBeZipped
)
$null = & "C:\Program Files\7-Zip\7z.exe" A -tzip $zipFile $toBeZipped
}
$Days = 60
$LastWrite = (Get-Date).Date.AddDays(-$Days)
$TargetFolder = "D:\Testing\*"
$Files = Get-Childitem $TargetFolder -Recurse |
Where-Object { $_.LastWriteTime -le $LastWrite } |
Select-Object -ExpandProperty Fullname
Zip "$($ENV:USERPROFILE)\Desktop\TEST.zip" $Files
I worked when I tested it on a VM and one physical machine. However, when I tried it on a different computer, it failed. This is what I got:
Program '7z.exe' failed to run: The filename or extension is too long
At C:\Users\Admin\Documents\zip help.ps1:23 char:9
+ $null = & "C:\Program Files\7-Zip\7z.exe" A -tzip $zipFile $toBeZippe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.
At C:\Users\Admin\Documents\zip help.ps1:23 char:1
+ $null = & "C:\Program Files\7-Zip\7z.exe" A -tzip $zipFile $toBeZippe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedEx
ception
+ FullyQualifiedErrorId : NativeCommandFailed
The script can't use 7-zip. The other computers had 7-Zip in the exact same file path so I am unsure of what my problem is. Any input will be appreciated.
Edit: I can confirm the error is because of the long file path. Tried my script on a file with shorter path and it worked just fine.
I was able to figure out what was causing this. The folder contained a lot of other folders inside of it. The -Recurse
made the script look in every folder, causing this problem. All I had to do was adjust the script to remove the -Recurse
and it worked.