识别Expand-Archive

时间:2018-03-15 22:36:09

标签: powershell error-handling

我正在使用PowerShell 5.我使用Expand-Archive来解压缩包含数千个文件的文件。一切都在大部分时间都很好用,但偶尔我们会在zip中获得错误的文件名。在我的测试用例中,zip文件中的pdf文件在名称中有一个冒号':',这会导致失败。

这是一个应该以静默方式运行的计划任务,仅在出现错误时报告。出错时,它应该完成,但发送错误警告。最理想的是,我想知道存档名称,以及存档中的哪个文件失败,因此我可以将其添加到报告中。有谁知道怎么做?

我尝试了这里描述的-WarningVariable开关:PowerShell Pscx Expand-Archive method failure detection但变量中没有内容。

我当前的代码发送报告,但报告仅包含归档的名称。我认为无法获取导致失败的归档文件的名称:

$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
    }
}

我也尝试过:

$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
            }
        }
    }           
}

如果我手动运行它,我可以在归档中获取问题文件的名称,因为它在尝试复制之前输出,但是try / catch不起作用,因为错误时会弹出一个应用程序屏幕停止脚本,不发送任何报告。

0 个答案:

没有答案