tags:

views:

452

answers:

4

How can I store a directory name in a variable inside batch file??

+2  A: 
set dirname=c:/some/folder

echo %dirname%

REM retrieve the last letter of the folder 
REM and save it in another variable

set lastLetter=%dirname:~-1%

echo %lastLetter%
dirkgently
What am I replacing for some/folder exactly????
Whatever folder name you want to store!
dirkgently
The name of the directory that you want to store?
Nick
Tks... Another question that I have is that let say I have "dirname" now. Is there a way that I can get the last letter of this???
Updated my answer with an example of retrieving the last letter. HTH.
dirkgently
Substring is possible in batch: take a look for example at this reference http://www.ss64.com/nt/syntax-substring.html
Valentin Jacquemin
@Valentin Jacquemin: That's exactly what my example does!
dirkgently
A: 

To return the directory where the batch file is stored use %~dp0

%0 is the full path of the batch file,

set src= %~dp0
echo %src%

I've used this one when I expect certain files relative to my batch file.

Jeff Hall
A: 

Without more precisions it's difficult to help you...

Maybe you want the current directory?

set name=%CD%
echo %name%
Valentin Jacquemin
A: 

Use the set command.

Example:

rem Assign the folder "C:\Folder1\Folder2" to the variable "MySavedFolder"
set MySavedFolder=C:\Folder1\Folder2

rem Run the program "MyProgram.exe" that is located in Folder2
 %MySavedFolder%\MyProgram.exe
rem Run the program "My Second Program.exe" that is located in Folder 2 (note spaces in filename)
"%MySavedFolder%\My Second Program.exe"
rem Quotes are required to stop the spaces from being command-line delimiters, but the command interpreter (cmd.exe) will still substitute the value of the variable.

To remove the variable, assign nothing to the name:

set MySavedFolder=

Since you are inside a batch file, I suggest surrounding your variable usage with setlocal and endlocal at the end of the file; this makes your environment variables local to the batch file and doesn't pollute the global environment namespace.

Jay Michaud