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

    20140508-Delphi-2007--Project-Options--Cannot-Edit-Application-Title-HelpFile-Icon-Theming

    20140430-Fiddler-Filter-Actions-Button-Run-Filterset-now

    20140424-Windows-7-free-disk-space

    More Photos
  • Pages

  • All categories

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

    Join 1,346 other followers

Archive for August 30th, 2011

Batch file to get parent directory (not the directory of the batch file, but the parent of that directory)

Posted by jpluimers on 2011/08/30

The problem solved here is two-fold:

  1. The ~dp syntax for getting the directory/path part only works for parameters and loop indexes, not on variables.
    You can work around this by having a 1-iteration for-loop.
  2. The :~ syntax for getting the substring works only for variables, not for parameters and loop indexes.
    You can work around this by assigning to a temporary variable.

Example:

  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

This will show:

  1. The directory of the batch file
  2. The directory but without the trailing backslash
  3. The parent directory of the batch file

Hope you can give this some use.

–jeroen

Posted in Batch-Files, Development, Power User, Scripting, Software Development | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 1,346 other followers

%d bloggers like this: