开发者

cmd: variable of open with

开发者 https://www.devze.com 2022-12-15 01:13 出处:网络
When, for example, i want a batch file to \'open\' a file. when i 开发者_如何学Gofor example drag and drop the file into the batch file, it should do some stuff with that file.

When, for example, i want a batch file to 'open' a file. when i 开发者_如何学Gofor example drag and drop the file into the batch file, it should do some stuff with that file.

Now, i need to know the variable. I know there is a variable for this kind of stuff; i just forgot it.

Can someone give me the variable please?

Thanks.


The first 9 parameters given to a batch file can be accessed by writing %1 through %9.

The complete command line argument is stored in %*.

For more information, see here.


Drag&Drop to a batch file can be a much more difficult job.
Because windows doesn't know how to add the files in the correct way.

If your files are simple, it works as expected.

1.txt
2 3.txt
4 & 5.txt


drag.bat 1.txt "2 3.txt" "4 & 5.txt"

But some filenames are confusing windows...

6,7.txt
8&9.txt

drag.bat 6,7.txt 8&9.txt
-- results in --
%1 = 6
%2 = 7.txt
%3 = 8
%4 =
The command "9.txt" can not be found

In the first moment it seems an impossible problem,
but it exists a solution.

The trick is to use the cmdcmdline variable instead of the parameters %1..%9
The cmdcmdline contains something like

cmd /c ""C:\dragTest\test.bat" C:\dragTest\1.txt "C:\dragTest\2 3.txt" 
C:\dragTest\6,7.txt C:\dragTest\8&9.txt"

So you can work with this, but you have to stop your batch after all, so the 9.txt can't be executed.

@echo off
setlocal ENABLEDELAYEDEXPANSION
rem Take the cmd-line, remove all until the first parameter
set "params=!cmdcmdline:~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 Or you can access the parameter with, but this isn't secure with special characters like ampersand
  rem call echo %%item_!count!%%
)

rem list the parameters
for /L %%n in (1,1,!count!) DO (
  echo %%n #!item_%%n!#
)
pause

REM *** EXIT *** is neccessary to prevent execution of "appended" commands
exit 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号