.BAT当前文件夹名称 [英] .bat current folder name

查看:628
本文介绍了.BAT当前文件夹名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的剧本的蝙蝠,我调用另一个脚本,并传递一个字符串参数

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?

推荐答案

如果你想你在哪里目前是目录,你可以从%CD% 。这就是你的当前工作目录。

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%

那么您可以在您的code使用%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%

此输出:


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

它的工作原理通过完整的路径,一次年底复制的字符,直到找到 \\ 分隔符。它既不pretty,也没有效率,但Windows批处理编程很少是: - )

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 :-)

修改

其实,有一个简单而非常有效的方法来获得最后一个组件名称。

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"

这篇关于.BAT当前文件夹名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆