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

Dog*_*ggo 1 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
Run Code Online (Sandbox Code Playgroud)

bri*_*ist 6

您不能对外部进程使用异常处理(这是什么robocopy.exe).

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

有关处理外部错误的信息,请参见此处的最后一节.

此处提供了robocopy退出代码列表,并提供以下信息:

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.
Run Code Online (Sandbox Code Playgroud)

我强烈建议您将/ LOG参数与Robocopy一起使用,以便创建该过程的完整日志文件.这个文件对于找出问题是非常宝贵的.