【问题标题】:A simple try catch doesn't work Powershell一个简单的 try catch 不起作用 Powershell
【发布时间】:2017-01-13 15:08:40
【问题描述】:

所以我正在使用 Powershell 进行 robocopy。我想要的只是写一个日志文件。 Robocopy 有效,但 try and catch 无效。这是我的 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

【问题讨论】:

  • ROBOCOPY 有 /LOG 或 /LOG+ 选项。你能用那个吗?我不明白你试图用 try catch 来完成什么。如果没有错误,则不会记录任何内容。
  • @ShawnEsterman 不,我不能使用 ROBOCOPY LOG 选项,因为我希望每天都有一个新的日志文件。我不能用 robocopy 做到这一点。但是,当在 try 短语中出现错误时,它不会被抓住。它会停止。
  • 我的意思是这是一个选项:robocopy.exe ... /LOG:"C:\users\boriv\Desktop\$(get-date -f dd-MM-yyyy)"跨度>

标签: powershell try-catch


【解决方案1】:

您不能对外部进程使用异常处理(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 参数 为了创建一个完整的进程日志文件。这个文件是 对于找出问题所在非常宝贵。

另外RoelVB添加了一条非常有用的评论:

请注意,对于 robocopy,退出代码是按位计算的,并且可以组合使用。例如,您可以获得退出代码 3,它是 1 和 2 的组合

【讨论】:

  • 请注意,对于 robocopy,退出代码是按位计算的,并且可以组合。例如,您可以获得退出代码 3,它是 1 和 2 的组合
  • @RoelVB 感谢几个月前的评论。我已将其编辑为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
相关资源
最近更新 更多