Technology2 min read

Puzzling out why a program doesn’t work when run from a batch file, but works when double-clicked from Explorer

By · Published by Everything Blog

In short

The customer's batch file program worked fine when double-clicked from Explorer but failed when run from a batch file. Changing the directory fixed the issue by explicitly changing the directory and then restoring the original directory.

Key points

  • The customer's batch file program worked fine when double-clicked from Explorer but faile…: The customer's batch file program worked fine when double-clicked from Explorer but failed when run from a batch file.
  • Changing the directory fixed the issue by explicitly changing the directory and then rest…: Changing the directory fixed the issue by explicitly changing the directory and then restoring the original directory.
  • The program looked for ancillary files relative to its current directory, but the batch f…: The program looked for ancillary files relative to its current directory, but the batch file ran it by its full path without changing the current directory.

Sources checked by our analysis pipeline: 1

A customer asked for help writing a batch file to launch a program. For some reason, the program displayed an error message when the batch file ran it, whereas it worked fine when they double-clicked the program from Explorer.

I immediately suspected that they were not setting the current directory.

Some time ago, I noted that when you double-click a file in Explorer, Explorer sets the current directory of the program to the directory containing the thing that you double-clicked. This is done to accomodate programs that look for ancillary files in the current directory. The example I had was a hypothetical LitWare Writer program that, when given an ABC.LIT file, looks for related files like ABC.LTC (the table of contents) and ABC.LDC (the custom dictionary) in the current directory.

This also happens if you double-click the .exe

file: The current directory is set to the directory that contains the executable.

My guess is that the customer’s program looks for ancillary files relative to its current directory, but the batch file ran the program by its full path without changing the current directory to match the program’s path.

The customer confirmed that explicitly changing the directory fixed the program. (More specifically, they used pushd

to change the directory and then popd

to restore the original directory.)

Bonus chatter: It didn’t come to it, but my second idea would have been to check whether the program had set a custom entry under App Paths

to ask for additional directories to be added to the PATH

environment variable when the program is run.

0 comments

Be the first to start the discussion.

Original source: devblogs.microsoft.com

Technology