In some situations, batch files are the only thing you have.
In this case, I needed the parent directory of a batchfile.
i.e. not the directory of the batch file itself, but the
echo batchfile=%0 echo full=%~f0 setlocal ::http://stackoverflow.com/questions/636381/what-is-the-best-way-to-do-a-substring-in-a-batch-file set Directory=%~dp0 echo Directory=%Directory% :: strip trailing backslash set Directory=%Directory:~0,-1% echo %Directory% :: ~dp does not work for regular environment variables: :: set ParentDirectory=%Directory:~dp% set ParentDirectory=%Directory:~dp% :: ~dp only works for batch file parameters and loop indexes for %%d in (%Directory%) do set ParentDirectory=%%~dpd echo ParentDirectory=%ParentDirectory% endlocal
The point is that the %~dp0 trick as explained in this StackOverflow answer on substrincgs in batch files only works for batch file parameters (starting with a single percentage sign: %0, %1, %4, etc) or for-loop indexes (starting with double percentage signs: %%1, %%d, etc). They don’t work for getting path portions of regular environment variables.
So I used the substring trick (as explained in the same answer), and then used a for loop (which will have one iteration) to get the path portion.
Note: The substrings trick only works on regular environment variables, not on parameters and loop indexes.
Note 2: I used setlocal/endlocal so the changed environment variables stay local to the batch file and won’t leak out to your command-prompt. If you need the value there, then remove the setlocal/endlocal, or use an “endlocal & set” command on a single line. Read the rest of this entry »