In this article I will show you how to get the folder executing the batch file and how to use it inside of it.

Get current directory from a batch file

I faced a problem with a batch file running against my continuous integration server (CI). The batch file below works great when I launch it manually through the command line.

sqlcmd -S .\SQLEXPRESS -i "attachDB.sql" -v database="ifacture" -v backupfile="ifacture.bak" -v root="%CD%"

Note: attachDB.sql and ifacture.bak are in the same folder. When I launch it from command line I am inside the batch folder. Thus all goes well.

When I execute this batch command, the continuous integration server fails because it is calling the batch file not directly from the batch folder. This is a problem since I don't want to hard code paths or make two different paths (one for the development environment, another for the CI one).

So, there is an environment variable which can be used and make it works wherever you are executing the batch file. ~dp0 ~dp0 works under batch files only and returns the current letter and path running the batch file.

Finally, adding this environment variable to my batch file allows me to tackle all the cases.

sqlcmd -S .\SQLEXPRESS -i "~dp0attachDB.sql" -v database="ifacture" -v backupfile="ifacture.bak" -v root="%CD%"
Last revised: 22 déc., 2024 06:55 History

Trackbacks

Discussion

No comments yet. Be the first!

No new comments are allowed on this post.