Doggo
Doggo

Reputation: 2321

A simple try catch doesn't work Powershell

So i'm doing a robocopy with Powershell. And all i want is to write a logfile. The Robocopy works but the try and catch doesnt work. Here is my Powershell-Code:

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

Upvotes: 4

Views: 3080

Answers (1)

briantist
briantist

Reputation: 47862

You can't use exception handling for an external process (which is what robocopy.exe is).

Instead, you should use $LASTEXITCODE to determine the status of the execution. Each individual external command has different exit codes that mean different things (though 0 nearly universally means Success).

See the very last section here for information on handling external errors.

A list of robocopy exit codes is available here and offers this information:

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.

I strongly recommend that you use the /LOG parameter with Robocopy in order to create a complete log file of the process. This file is invaluable for finding out what went wrong.

Also RoelVB added a very useful comment:

Note that the exit codes are bit wise for robocopy and can be combined. You could for example get exit code 3, which is a combination of 1 and 2

Upvotes: 8

Related Questions