Power to Build

Home » Misc » Windows Tips & Tricks: Script BaseDir

Windows Tips & Tricks: Script BaseDir

When we migrated to Windows 7, there were some surprises. One of them was the current directory in a batch file. Earlier, current directory stayed where you ran the script from. In Windows 7, it always ​seemed to ​
default​ ​
to the Windows\Sytem32 folder​, thus c
aus​ing ​
some "command not found" errors, wrong files etc. Below statements help to overcome that.

SET ​​

REM Windows 7 may default to C:\Windows\System32, so force back to the script directory


%~dp0 is an interesting concoction in Windows​ (called Parameter modifier or expansion)​
to find the base directory, where the script is run from.​

Here are some interesting variations:

%0 being the Script path (full) that we are running currently.

%~p0 = the path of the script (minus filename or the drive letter) – just the directory name.

​%d0 = the drive letter where the script is being run from.

And the one we used here, %dp0 means the drive letter + the path (minus file name), which is what the basedir is – the directory where the script resides.​​

Parameter modifier ​is a subject in itself. We will see it on another post.​ We often use to these dissect a path into its parts to be used in scripts.

While we are on the subject of getting BaseDir, to do this on Linux, you would have used something like this:​

BASEDIR=$(dirname $0)

​Where dirname ​extracts the directory part of a path and $0 refers to the script that’s being run.

Comments, please?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: