A simple try catch doesn’t work Powershell

Question:

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:

Answer:

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:

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

Source:

A simple try catch doesn’t work Powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply