如何接收,即使最奇怪的命令行参数? [英] How to receive even the strangest command line parameters?
问题描述
如在其他线程<一个讨论href=\"http://stackoverflow.com/questions/3813370/how-to-avoid-cmd-exe-inter$p$pting-shell-special-characters-like\">How避免CMD.EXE间preting shell特殊字符,如&LT; > ^
它不容易从命令行获得的所有参数。
as discussed in an other thread How to avoid cmd.exe interpreting shell special characters like < > ^ it is not easy to get all parameters from the command line.
一个简单的
set var=%1
set "var=%~1"
是不够的,如果你有一个像
are not enough, if you have a request like
myBatch.bat abc"&"^&def
我有一个解决方案,但它需要一个临时文件,并且也没有防弹
I have one solution, but it needs a temporary file, and it is also not bullet proof.
@echo off
setlocal DisableDelayedExpansion
set "prompt=X"
(
@echo on
for %%a in (4) do (
rem #%1#
)
) > XY.txt
@echo off
for /F "delims=" %%a in (xy.txt) DO (
set "param=%%a"
)
setlocal EnableDelayedExpansion
set param=!param:~7,-4!
echo param='!param!'
它失败,类似的 myBatch.bat%A ,它显示的 4 未在%A
在这种情况下,一个简单的回声%1 会的工作。结果
这显然for循环,但我不知道该如何改变这种状况。结果
或许存在另一种简单的解决方案。
in this situation a simple echo %1 would work.
It's obviously the for-loop but I don't know how to change this.
Perhaps there exists another simple solution.
我不需要这个解决一个实际的问题,但我喜欢在每个情况防弹解决方案,不仅在大多数情况下。
I don't need this to solve an actual problem, but I like solutions that are bullet proof in each situation, not only in the most cases.
推荐答案
我不认为任何人发现了任何漏洞,除了不能在参数读取换行符:
I don't think anyone found any holes in this, except for the inability to read newlines in the parameters:
@echo off
setlocal enableDelayedExpansion
set argCnt=1
:getArgs
>"%temp%\getArg.txt" <"%temp%\getArg.txt" (
setlocal disableExtensions
set prompt=#
echo on
for %%a in (%%a) do rem . %1.
echo off
endlocal
set /p "arg%argCnt%="
set /p "arg%argCnt%="
set "arg%argCnt%=!arg%argCnt%:~7,-2!"
if defined arg%argCnt% (
set /a argCnt+=1
shift /1
goto :getArgs
) else set /a argCnt-=1
)
del "%temp%\getArg.txt"
set arg
以上来自一个热闹DosTips讨论 - <一个href=\"http://www.dostips.com/forum/viewtopic.php?p=13002#p13002\">http://www.dostips.com/forum/viewtopic.php?p=13002#p13002. DosTips用户利维乌·想出了一个关键 SETLOCAL DISABLEEXTENSIONS
片。
The above comes from a lively DosTips discussion - http://www.dostips.com/forum/viewtopic.php?p=13002#p13002. DosTips user Liviu came up with the critical SETLOCAL DisableExtensions
piece.
这篇关于如何接收,即使最奇怪的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!