一个简单的尝试捕获并不起作用Powershell

时间:2017-01-13 15:08:41

标签: powershell try-catch

所以我用Powershell做了一个robocopy。我只想写一个日志文件。 Robocopy工作,但尝试和捕获不起作用。这是我的Powershell代码:

function Write-Log{[CmdletBinding()]
Param(
[Parameter(Mandatory=$False)]
[ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
[String]
$level = "INFO",

[Parameter(Mandatory=$True)]
[string]
$message ,

[Parameter(Mandatory=$True)]
[string]
$logfile
)

$timeStamp = (Get-Date).toString("dd.MM.yyyy HH:mm:ss")
$line = "$timeStamp $level $message"
if($logfile) {
    Add-Content $logfile -Value $line
} else {
    Write-Output $line
}}


try {C:\WINDOWS\SysWOW64\robocopy.exe "C:\Users\boriv\Desktop\por" "C:/users/boriv/desktop/1" robocopy *.* /MIR /EFSRAW /DCOPY:DAT /A+:R /A-:AE /IA:ACEHNORST /V /BYTES}

catch { Write-Log -message "Der Kopiervorgang war nicht erfolgreich" -logfile "C:\users\boriv\Desktop\$(get-date -f dd-MM-yyyy).txt" -level ERROR}

Write-Log -message "Der Kopiervorgang war erfolgreich" -logfile "C:\users\boriv\Desktop\$(get-date -f dd-MM-yyyy).txt" -level INFO

1 个答案:

答案 0 :(得分:6)

您不能对外部流程使用异常处理(robocopy.exe就是这样)。

相反,您应该使用$LASTEXITCODE来确定执行的状态。每个单独的外部命令都有不同的退出代码,这些代码表示不同的东西(尽管0几乎普遍意味着成功)。

See the very last section here有关处理外部错误的信息。

A list of robocopy exit codes is available here并提供此信息:

0 No errors occurred and no files were copied.
1 One of more files were copied successfully.
2 Extra files or directories were detected.  Examine the log file for more information.
4 Mismatched files or directories were detected.  Examine the log file for more information.
8 Some files or directories could not be copied and the retry limit was exceeded.
16 Robocopy did not copy any files.  Check the command line parameters and verify that Robocopy has enough rights to write to the destination folder.
     

我强烈建议您使用带有Robocopy的/ LOG参数   命令创建进程的完整日志文件。这个文件是   找出问题所在是非常宝贵的。