【问题标题】:Drag and drop in a batch file - expanding the variable of this code problem在批处理文件中拖放-扩展此代码问题的变量
【发布时间】:2020-01-24 01:02:25
【问题描述】:

这是来自这个很好的答案的some code,它不能解决我的情况。

请参阅我试图解决此问题的 22 行。

@echo off
setlocal ENABLEDELAYEDEXPANSION
rem *** Take the cmd-line, remove all until the first parameter
rem *** Copy cmdcmdline without any modifications, as cmdcmdline has some strange behaviour
set "params=!cmdcmdline!"
set "params=!params:~0,-1!"
set "params=!params:*" =!"
set count=0
rem Split the parameters on spaces but respect the quotes
for %%G IN (!params!) do (
  set /a count+=1
  set "item_!count!=%%~G"
  rem echo !count! %%~G
  )
rem list the parameters
for /L %%n in (1,1,!count!) DO (
  rem Original line, works fine
  rem echo %%n #!item_%%n!#
  rem This works fine with !item_%%~n!
  echo !item_%%~n!
  rem This doesn't when I try to expand n to the path.
  echo !item_%%~pn!
)
pause
REM ** The exit is important, so the cmd.exe doesn't try to execute commands after ampersands
exit

理想情况下,我希望将 !item_%%n! 变量扩展为 !item_%%~pn! 以获取路径,但我不知道如何修改该代码来执行此操作。

我认为item 变量保存了路径,然后n 变量通过它们计数。


我希望能够像平常一样扩展到这些其他人:

%%~A         &rem expands %%A removing any surrounding quotes (")
%%~dA        &rem expands %%A to a drive letter only
%%~fA        &rem expands %%A to a fully qualified path name
%%~pA        &rem expands %%A to a path only
%%~nA        &rem expands %%A to a file name only
%%~xA        &rem expands %%A to a file extension only
%%~sA        &rem expanded path contains short names only
%%~aA        &rem expands %%A to file attributes of file
%%~tA        &rem expands %%A to date/time of file
%%~zA        &rem expands %%A to size of file
%%~dpA       &rem expands %%A to a drive letter and path only
%%~nxA       &rem expands %%A to a file name and extension only
%%~fsA       &rem expands %%A to a full path name with short names only
%%~dp$dir:A  &rem searches the directories listed in the 'dir' environment variable and expands %%A to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
%%~ftzaA     &rem expands %%A to a DIR like output line

【问题讨论】:

    标签: batch-file


    【解决方案1】:

    !item_%%n! 的扩展以另一种方式工作。

    首先%%n 将扩展为一个数字。
    然后!item_<number>! 将被展开。

    如果要使用参数语法,则必须先将结果移动到参数中。

    echo !item_%%~n!
    FOR /F "delims=" %%I in ("!item_%%n!") DO ECHO path: %%~dpI
    

    【讨论】:

    • 实际上你使用了 FOR 变量,而不是参数。两者具有相同的修饰符语法。显然,如果使用 call :routine "!item_%%n!! 而不是 FOR /F,则可以使用参数。
    • @dbenham Nitpicker,但显然你是对的 :-)
    • 无论如何你都得到了我的加一:-)
    • 文件名开头有; 时会出现问题。有没有办法在这个答案中解决这个问题?
    • @Ste 这里的问题是drag&drop 本身。带有任何分号的文件不会被自动引用,因此分号在for %%G IN (!params!) 中作为分隔符处理。你可以通过一个全功能的行解析器或一点点替换魔法来处理这个问题
    猜你喜欢
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2018-08-02
    • 2011-07-08
    相关资源
    最近更新 更多