windows .bat 当前文件夹名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3848597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:39:19  来源:igfitidea点击:

.bat current folder name

windowsbatch-file

提问by Berming

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

在我的 bat 脚本中,我正在调用另一个脚本并向它传递一个字符串参数

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?

如您所见,字符串参数包含从中调用脚本的文件夹的名称。将此动态插入此文件夹名称传递给脚本的正确方法是什么?

回答by paxdiablo

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

如果您想要当前所在的目录,可以从%cd%. 那是您当前的工作目录。

If you're going to be changingyour 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%).

那么您可以%startdir%在您的代码中使用,而不管以后有任何更改(影响%cd%)。



If you just want to get the lastcomponent 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 Settings\Pax> testprog.cmd
    startdir = C:\Documents and Settings\Pax
    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 :-)

它的工作原理是从完整路径的末尾复制字符,一次一个,直到找到\分隔符。它既不漂亮也不高效,但 Windows 批处理编程很少是:-)

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"