如何接收最奇怪的命令行参数

如何接收最奇怪的命令行参数

本文介绍了如何接收最奇怪的命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如另一个线程所讨论的那样
从命令行获取所有参数并不容易。

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

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

echo%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讨论 - ? DosTips用户Liviu提出了关键的 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.

这篇关于如何接收最奇怪的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 12:00