I am using PowerShell 5. I am using Expand-Archive to unzip files containing several thousand files. All works well most of the time but occasionally we get a bad filename in a zip. In my test-case the pdf file within the zip file has a colon ':' in the name, which causes the failure.
This is a scheduled task that should run silently, only reporting back if there is an error. On error, it should complete, but send an error warning. Optimally I would like to know both the archive name, and on which file within the archive it failed so I can add it to the report. Does anyone know how to do this?
I tried the -WarningVariable switch described here: PowerShell Pscx Expand-Archive method failure detection but had no content in the variable.
My current code sends a report, but the report contains only the name of the archive. I see no way to obtain the name of the file within the archive that causes the failure:
$file_list | ForEach-Object {
try{
Expand-Archive -Path $_.FullName -DestinationPath $input_temp -force
}
catch {
Send-MailMessage -from "email@address" -to "email@address" -subject $subject -body "File ($need_to_know_on_which_file_the_extract_failed) failed to extract from $($_.FullName)" -SmtpServer smtp.server
}
}
I also tried:
$shell = new-object -com shell.application
$zip = $shell.NameSpace($zipFile)
$files = $zip.items().count
if ($files -gt 0) {
foreach($item in $zip.items()){
if ($item.name -like "*.pdf") {
Write-Verbose "File: $($item.name)"
try {
$shell.Namespace($destination).copyhere($item,0x14)
}
catch {
Send-MailMessage -from "email@address" -to "email@address" -subject $subject -body "File ($need_to_know_on_which_file_the_extract_failed) failed to extract from $($_.FullName)" -SmtpServer smtp.server
}
}
}
}
This lets me get the name of the problem file within the archive if I run it manually, since it outputs just before trying the copyhere, but the try/catch doesn't work because on error it pops up an application screen which stops the script and no report is sent.