Search code examples
powershellbatch-fileexit-codestart-process

ExitCode from Batchfile is weird


I'm trying to run a batch file from a powershell script and check if there has been any error during the runtime.

Right now, I'm doing it by the following code:

$job = Start-Process -FilePath "C:\Test\Testfile_2.bat" -Wait -passthru;
$job.ExitCode

This works... or at least, nearly.

While I get the exitCode, it really only gives me information about the last command ran by the batchfile. Let me explain it.

If I do the following in my batchfile:

MKDIR C:\Test\Testdir

If I run this, I'll get exitCode "0" the first time I run it, for all the following runs I get "1", since the directory already exists. But if I add a simple CD to the end of the batchfile:

MKDIR C:\Test\Testdir
CD C:\

I will ALWAYS get exitCode "0", since the CD command works everytime. So even tho the directory exists and it would give me an error in the cmd, there's no error in the exitCode. Is there a way to check for any errors during the runtime of a batchfile with powershell, or do I have to code my batchfile the way that it cancels as soon as there's an error and immediatly returns an error exitCode?

Thanks for any help or advises!


Solution

  • In order for an external program, such as your powershell command, to know what is happening while the batch script is being run, you need to actually script this into your batch file in order to determine what should happen during certain errors.

    For instance, your powershell example simply launches the batch, waits for it to complete and echo the last errorlevel, which you batch exited with, though you might have numerous different errorlevels during the script being run.

    if however your batch handles errors internally, like the below example, you could do something with it:

    ....
    ping google.ca >nul
    if %errorlevel% neq 0 (
    exit /b %errorlevel%
    ) else (
    ....