1

I have a batch file where I call one application by passing certain arguments.

Here is the content of my sample.batch file

cd C:\Program Files\MyApplication
"C:\Program Files\MyApplication\Application.exe" -e -p "Application Projects/Testing/General/Notepad" -rm "Close Notepad"

Here I need to change my current working directory to the folder where Application.exe lives so that It finds certain required JARs which is located in that folder.Is it best practice to do so?Changing the current work directory before executing a batch file.

Srikant Barik
  • 133
  • 2
  • 12

2 Answers2

6

Try

pushd C:\Program Files\MyApplication
...
popd

as another choice.

best practice is a matter of both opinion and circumstance

Magoo
  • 77,302
  • 8
  • 62
  • 84
6

One method is what Magoo and Stephan have suggested already:

pushd "%ProgramFiles%\MyApplication"

rem Other commands.

popd

This solution works even for UNC paths with command extensions enabled as by default as PUSHD temporarily maps the network share to a drive letter and makes this network drive the current directory.

Another solution is using SETLOCAL, CD and ENDLOCAL which has the advantage of all modifications of environment variables, command extensions and delayed expansion done by the commands between setlocal and endlocal don't matter for the commands after endlocal command line.

setlocal EnableExtensions DisableDelayedExpansion
cd /D "%ProgramFiles%\MyApplication"

rem Other commands running in their own environment, here running with command
rem extensions explicitly enabled and delayed expansion explicitly disabled.

endlocal

The command ENDLOCAL restores also the current directory as being set on execution of SETLOCAL.

See the answer on change directory command cd ..not working in batch file after npm install with more details about PUSHD (push directory), POPD (pop directory), SETLOCAL (setup local environment), CD (change directory) and ENDLOCAL (end local environment).

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • cd /?
  • endlocal /?
  • rem /?
  • setlocal /?
  • popd /?
  • pushd /?
Community
  • 1
  • 1
Mofi
  • 46,139
  • 17
  • 80
  • 143