The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My work

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,799 other followers

Archive for August 9th, 2011

batch files: getting directory and parent directory

Posted by jpluimers on 2011/08/09

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
  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%

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 »

Posted in Batch-Files, Development, Scripting, Software Development | 2 Comments »

%d bloggers like this: