.bat current folder name

In my bat script, I call another script and pass it a string parameter

cscript log.vbs "triggered from folder <foldername> by Eric" 

The string parameter that you see contains the name of the folder from which the script is being called. What is the proper way to pass this dynamically insert this folder name into the script?

+6
windows batch-file
source share
2 answers

If you need the directory you are currently in, you can get it with %cd% . This is your current working directory.

If you are going to change the current working directory during script execution, just save it at the beginning:

 set startdir=%cd% 

then you can use %startdir% in your code regardless of any changes later (which affect %cd% ).


If you just want to get the last component of this path (as per your comment), you can use the following as a baseline:

  @setlocal enableextensions enabledelayedexpansion
     @echo off
     set startdir =% cd%
     set temp =% startdir%
     set folder =
 : loop
     if not "x% temp: ~ -1%" == "x \" (
         set folder =! temp: ~ -1 !! folder!
         set temp =! temp: ~ 0, -1!
         goto: loop
     )
     echo.startdir =% startdir%
     echo.folder =% folder%
     endlocal && set folder =% folder%

It is output:

  C: \ Documents and Settings \ Pax> testprog.cmd
     startdir = C: \ Documents and Settings \ Pax
     folder = Pax

It works by copying characters from the end of the full path, one at a time, until it finds the delimiter \ . It is neither beautiful nor efficient, but batch programming of Windows is rare :-)

EDIT

In fact, there is a simple and very effective method for getting the last name of a component.

 for %%F in ("%cd%") do set "folder=%~nxF" 

Not a problem for this situation, but if you are dealing with a variable containing a path that may or may not end with \ , then you can guarantee the correct result by adding \.

 for %%F in ("%pathVar%\.") do set "folder=%~nxF" 
+18
source share

All Articles