Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

A simple

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!'

It fails with something like myBatch.bat %a, it display 4 not the %a

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
880 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...