Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

windows - .bat current folder name

In my bat script, I'm calling another script and passing it a string parameter

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

The string parameter as you can see contains the name of the folder from which the script is being called. What's the right way to pass this dynamically insert this folder name to the script?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want the directory where you're currently at, you can get that from %cd%. That's your current working directory.

If you're going to be changing your current working directory during the script execution, just save it at the start:

set startdir=%cd%

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


If you just want to get the last component of that 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%

This outputs:

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

It works by copying the characters from the end of the full path, one at a time, until it finds the separator. It's neither pretty nor efficient, but Windows batch programming rarely is :-)

EDIT

Actually, there is a simple and very efficient method to get the last component name.

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

Not an issue 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 appending .

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...