从外部命令捕获错误

时间:2016-03-20 14:53:31

标签: powershell

如果我运行此功能(没有try..catch):

executezipFullBackup -PathFileLocation "Z:\" -PathSaveBackup "E:\" -NameOfBackup "MyNASStorage"

PoweShell给我这个错误:

sz : 
At C:\PowerShellF\zipFunction.ps1:6 char:9
+         sz a -t7z "$PathSaveBackup\$NameOfBackup" "$PathFileLocation"  #backup
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

ERROR:
Duplicate filename on disk:
BackupTest\private\103.tmp\usr\bin\mail
BackupTest\private\103.tmp\usr\bin\Mail

这个错误对我来说没问题,因为我知道这一步有什么问题。

但我的问题是,如果我将此脚本放在try..catch中,我就不会收到此错误。 例如:

$ErrorActionPreference = "Stop";      #this is for Try Catch
try {
    zipFullBackup -PathFileLocation "$PathFileLocation" -PathSaveBackup "$PathSaveBackup" -NameOfBackup "$NameOfBackup"          
} catch {
    $MyError = ($Error[0] | Out-String);
    Write-Host "$MyError"
}

我得到这样的错误:

sz : 
At C:\PowerShellF\zipFunction.ps1:6 char:9
+         sz a -t7z "$PathSaveBackup\$NameOfBackup" "$PathFileLocation" #backup
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

这个错误对我来说还不够,因为我没有看到错误!我不明白这一点:

ERROR:
Duplicate filename on disk:
BackupTest\private\103.tmp\usr\bin\mail
BackupTest\private\103.tmp\usr\bin\Mail

如何让try..catch显示此错误?

1 个答案:

答案 0 :(得分:-1)

该错误消息不是PowerShell错误/异常的一部分,但是消息7zip本身会打印到STDOUT。因此,即使您设置了try..catch,也无法抓住$ErrorActionPreference = 'Stop'块。

您可以做的是在变量中收集命令输出:

$msg = zipFullBackup ...