Need help with parameter arguments

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Adrianvdh
Posts: 177
Joined: 16 May 2013 13:00

Need help with parameter arguments

#1 Post by Adrianvdh » 12 Jun 2014 08:43

Hey everyone...
Well I got this code last year from this forum but it is used for a "call" parameters not the actual batch file.
I need this for my batch file to support multiple arguments at one call..

commandline: "C:\file.bat" /r

Code: Select all

setlocal enableextensions enabledelayedexpansion
set "/r="&set "/u="&set "/c="&set "/d="&set "/n="&set "/?="
for %%a in (%*) do (
   if "%%~a"=="/r" set "/r=true"
   REM if "%%~a"=="/u" set "/u= "
   REM if "%%~a"=="/c" set "/c= "
   REM if "%%~a"=="/d" set "/d= "
   REM if "%%~a"=="/n" set "/n= "
   REM if "%%~a"=="/?" set "/?= "
)
REM just to test the output
if defined /r (echo hello &pause )


So I think that the code is broken.. All I need is a simple light parameter system.
Thanks :)

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Need help with parameter arguments

#2 Post by Squashman » 12 Jun 2014 09:31

I do recall Dave or someone doing a thread about using switches as command line arguments.

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Need help with parameter arguments

#3 Post by Squashman » 12 Jun 2014 10:01

Hmmm. I just tested your code and it works fine on my computer.
Well it works for all but the "/?"

Code: Select all

@echo off
setlocal enableextensions enabledelayedexpansion
set "/r="&set "/u="&set "/c="&set "/d="&set "/n="&set "/?="
for %%a in (%*) do (
   if "%%~a"=="/r" set "/r=true"
   if "%%~a"=="/u" set "/u=true"
   if "%%~a"=="/c" set "/c=true"
   if "%%~a"=="/d" set "/d=true"
   if "%%~a"=="/n" set "/n=true"
   if "%%~a"=="/?" set "/?=help"
)
REM just to test the output
set "/"
pause

Code: Select all

C:\BatchFiles>switches.bat /r /u /c /d /n /?
/c=true
/d=true
/n=true
/r=true
/u=true
Press any key to continue . . .

Adrianvdh
Posts: 177
Joined: 16 May 2013 13:00

Re: Need help with parameter arguments

#4 Post by Adrianvdh » 12 Jun 2014 10:44

How would I get the "/?" to work then?

Edit:

Alright never mind, I fixed it :)

Code: Select all

set "/r="&set "/u="&set "/c="&set "/d="&set "/n="&set "/?="
if "%~1"=="/?" goto ListPar
for %%a in (%*) do (
   if "%%~a"=="/r" set "/r= "
   if "%%~a"=="/u" set "/u= "
   if "%%~a"=="/c" set "/c= "
   if "%%~a"=="/d" set "/d= "
   if "%%~a"=="/n" set "/n= "
)
if defined /r (echo hello &pause )

Adrianvdh
Posts: 177
Joined: 16 May 2013 13:00

Re: Need help with parameter arguments

#5 Post by Adrianvdh » 12 Jun 2014 11:22

Alright I think this is the best I have come up with, it works well :)

Code: Select all

set "/r="&set "/u="&set "/c="&set "/d="&set "/n="
if not "%~1"=="" (
   if "%~1"=="/?" goto ListPar
   for %%a in (%*) do (
      if "%%~a"=="/r" set "/r=true"
      if "%%~a"=="/u" set "/u=true"
      if "%%~a"=="/c" set "/c=true"
      if "%%~a"=="/d" set "/d=true"
      if "%%~a"=="/n" set "/n=true"
   )
if not defined %%a (
   echo The syntax of the command is incorrect.
   goto :eof )
)
if defined /r echo r
if defined /u echo u
if defined /c echo c
if defined /d echo d
if defined /n echo n
Last edited by Adrianvdh on 12 Jun 2014 14:03, edited 1 time in total.

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Need help with parameter arguments

#6 Post by Squashman » 12 Jun 2014 11:53

You don't need this anymore.
&set "/?="

Adrianvdh
Posts: 177
Joined: 16 May 2013 13:00

Re: Need help with parameter arguments

#7 Post by Adrianvdh » 12 Jun 2014 14:03

Oh right, completely forgot about that :)

But I have another question. How would I have a rule set?

Where '/r /c /n' can only work together and '/u /d' can only also work together..

for example:
comandline: "C:\file.bat /r /u"

Code: Select all

echo The syntax of the command is incorrect.

I have no idea of an efficient way to do this without a whole bunch of 'if' statements.
Is there not kind of 'for' block I can implement?

carlsomo
Posts: 91
Joined: 02 Oct 2012 17:21

Re: Need help with parameter arguments

#8 Post by carlsomo » 24 Jun 2014 23:29

Here is an example of how to handle switches that may require a following switch or argument
Attn to:

call :parse %*

and %AndShift% toggle

and calling :labels in the parse routine

This is a Choice replacement routine for XP that handles Win 7-8 and Vista formats as well:

Code: Select all

@echo off&goto :main
:Choose.cmd [/c Choices] [/n] [/cs] [/t] [/d choice] [/m "Prompt"]
:SyntaxMessage
echo(
echo(CHOOSE [/C choices] [/N] [/CS] [/T timeout] [/D choice] [/M "Prompt"]
echo(
echo(Description:
echo(   This tool allows users to select one item from a list
echo(   of choices and returns the index of the selected choice.
echo(
echo(Parameter List:
echo(   /C    choices       Specifies the list of choices to be created.
echo(   or /C:choices       Default list is "YN". If a single '.' is passed
echo(   or /C .             the tool will return the decimal code of the
echo(                       Ascii character entered via the errorlevel.
echo(
echo(   /N                  Hides the list of choices in the prompt.
echo(                       The message before the prompt is displayed
echo(                       and the choices are still enabled.
echo(
echo(   /CS or /S           Enables case-sensitive choices to be selected.
echo(                       By default, the utility is case-insensitive.
echo(
echo(   /T    timeout       The number of seconds to pause before a default
echo(                       choice is made. Acceptable values are from 0 to
echo(                       9999. If 0 is specified, there will be no pause
echo(                       and the default choice is selected.
echo(
echo(   /D    choice        Specifies the default choice after nnnn seconds.
echo(                       Character must be in the set of choices specified
echo(                       by /C option. Default choice will also be used if
echo(                       the Enter key is pressed instead of a choice.
echo(
echo(   /M    "Text msg"    Specifies the message to be displayed before
echo(   or    "Text msg"    the prompt. If not specified, the utility
echo(                       displays only a prompt.
echo(
echo(   /?                  Displays this help message.
echo(
echo(   NOTE:
echo(   The ERRORLEVEL environment variable is set to the index of the
echo(   key that was selected from the set of choices. The first choice
echo(   listed returns a value of 1, the second a value of 2, and so on.
echo(   If the user presses a key that is not a valid choice, the tool
echo(   does not sound a warning beep. If tool detects an error condition,
echo(   it returns an ERRORLEVEL value of 255. If the user presses
echo(   CTRL+BREAK or CTRL+C, or presses the Escape key the tool returns
echo(   an ERRORLEVEL value of -27. If Enter is pressed the default
echo(   choice's Index will be returned. If no default is specified
echo(   then an errorlevel of 1 is returned ^(the first choice in the list^)
echo(   When you use ERRORLEVEL parameters in a batch program, list
echo(   them in decreasing order. Supports prior Choice.exe format as well
echo(
echo(Examples:
echo(   CHOOOSE /?
echo(   CHOOOSE /C YNC /M "Press Y for Yes, N for No or C for Cancel."
echo(   CHOOOSE /T 10 /C ync /CS /D y
echo(   CHOOOSE /C ab /M "Select a for option 1 and b for option 2."
echo(   CHOOOSE /C:ab /N "Select a for option 1 and b for option 2."
exit/b

:Main
if "%~1"=="/?" call :SyntaxMessage &exit/b 255
setlocal enableextensions enabledelayedexpansion
call :parse %*
if %errorlevel% lss %_OK% endlocal&exit/b 255
if defined ShowChoices set "ShowChoices=%ChoiceList%"
<nul set/p=%msg%%ShowChoices%
:Process Choice
call :GetKey %Timer%&set/a key=!errorlevel!
if %key% equ %Esc% exit/b -%Esc%
if %key% equ %CTRL_C% exit/b -%Esc%
if defined dot exit/b %key%
if %key% equ %Enter% (set Choice=%DefaultChoice%) else (
  if %key% lss 48 goto :Process
  call :Dec2Ascii %key% Choice
)
set /a ChoiceNum=0
for /l %%$ in (1,2,%LastChoice%) do (
  set/a ChoiceNum+=1
  call set "comp=%%ChoiceList:~%%$,1%%"
  if %CaseSense% "%choice%" equ "!comp!" (
    <nul set/p=%Choice%
    goto :endMain
  )
)
goto :Process
:endMain
endlocal&exit/b %ChoiceNum%

:GetKey WaitTime
if "%~1"=="" %GetKey.exe%&exit/b !errorlevel!
Set/a Delay=%~1*1000
call :Timer %Delay% "%GetKey.exe% /n"&exit/b !errorlevel!

:Parse command line
set "msg="
set/a _OK=0,AndShift=1,colon=0,NotInteger=-100,Enter=13,Esc=27,CTRL_C=3
set/a GetKeyError=-255,ShowChoices=1,TimeOut=13,DefaultIndex=1
set "VALID_CHOICES=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
set "DefaultChoice="
set "dot="
set "Timer="
set "ChoiceList=[Y,N]? "
set/a LastChoice=3
set "CaseSense=/i"
set "VALID_SWITCHES=/C /C: /N /CS /S /T /D /M"
set "GetKey.exe=GetKey.exe"
:Shift
set "var=%~1"
if not defined var call :SetGlobalVariables GetKey.exe&exit/b !errorlevel!
for %%A in (%VALID_SWITCHES%) do (
  set/a SwitchError=%_OK%
  if /i "%var:~0,3%" equ "%%A" call :Switch_%%A "%~2"&set/a SwitchError=!errorlevel!
  if !SwitchError! lss %_OK% exit/b !SwitchError!
  if !SwitchError! equ %AndShift% (shift)
)
if /i "%var:~0,1%" neq "/" if /i "%var%" neq "." if not defined msg set "msg=%var%"
shift&goto :Shift

:Switch_/c:
set "Choices=%var:~3%
if defined Choices set/a colon=1
:Switch_/C
if not defined Choices set "Choices=%~1"
if defined Choices (
  if "!Choices:~0,1!" neq "/" (
    if "!Choices!" equ "." set dot=.&set ChoiceList=&exit/b 255
    call :ValidateChoices Choices
    if !errorlevel! gtr 0 (
      set/a LastChoice=!errorlevel!
      set "ChoiceList=!Choices!"
      set DefaultChoice=!Choices:~1,1!
      set/a colon=%AndShift%-%colon%
      exit/b !colon!
    )
    goto :InValidChoices
  )
)
goto :NoChoicesError

:Switch_/N
set "ShowChoices=" &exit/b %_OK%

:Switch_/CS
:Switch_/S
set CaseSense=&exit/b %_OK%

:Switch_/T
set "Timer=%~1"
if defined Timer if "!Timer:~0,1!" neq "/" (
  call :IsInteger !Timer!&if !errorlevel! equ %_OK% exit/b %AndShift%
)
goto :TimerError

:Switch_/D
set DefaultChoice=%~1&if defined DefaultChoice (
  set DefaultChoice=!DefaultChoice:~0,1!&if !DefaultChoice! neq "/" exit/b %AndShift%
)
goto :DefaultError

:Switch_/M
set msg=%~1&if defined msg if "!msg:~0,1!" neq "/" exit/b %AndShift%
goto :MessageError

:SetGlobalVariables GetKey.exe
if defined DefaultChoice (
  call :CharInString %DefaultChoice% "ChoiceList" %CaseSense%
  if !errorlevel! neq %_OK% goto :DefaultChoiceError
)
if not exist %~1 if exist %~$PATH:1 (set %~1=%~$PATH:1) else (
  if exist %TEMP%\%~1 (set %~1=%TEMP%\%~1) else (
    call :Create %~1
    if !errorlevel! neq %_OK% echo(Error: %~1 could not be created&exit/b %GetKeyError%
  )
)
exit/b %_OK%

:TimerError
echo(ERROR: Invalid syntax. Valid range for /T is 0 - 9999.
goto :TypeChoose

:NoChoicesError
echo(ERROR: Invalid syntax. Value expected for '/c'.
goto :TypeChoose

:MessageError
echo(ERROR: Invalid syntax. Value expected for '/m'.
goto :TypeChoose

:DefaultError
echo(ERROR: Invalid syntax. Value expected for '/d'.
goto :TypeChoose

:DefaultChoiceError
echo(ERROR: Invalid syntax. Default choice is not found in the specified choices.
goto :TypeChoose

:InvalidChoices
echo(ERROR: Invalid choice. The valid choice characters are: a-z, A-Z, 0-9.
goto :TypeChoose

:TypeChoose
echo(Type "CHOOSE /?" for usage. &exit/b %GetKeyError%

::**********************************::
::*******||  SUBROUTINES   ||*******::
::**********************************::

:ValidateChoices "ChoiceList"
if %~1=="" exit /b %GetKeyError%
setlocal
set "Build="
call set "chc=%%%~1%%"
call :strlen %chc%&set/a len=!errorlevel!-1
for /l %%a in (0,1,%len%) do (
  call set #=%%chc:~%%a,1%%
  call :CharInString !#! VALID_CHOICES
  if !errorlevel! neq %_OK% exit/b !errorlevel!
  set "Build=!Build!!#!,"
)
set "Build=[%Build:~0,-1%]? "
set/a len=%len% * 2 + 1
endlocal&call set %~1=%Build%&exit/b %len%

:CharInString char "String" /cs
setlocal
if "%~2"=="" exit/b -255
set "char=%~1"
call set "string=%%%~2%%"
if not defined string exit/b -255
echo %string%|find %3 "%char%">nul
exit/b -%errorlevel%

:Strlen Returns length of string in errorlevel
setlocal&set "#=%*"
if not defined # exit /b 0
set/a len=0
:loop
set/a len+=1
set "#=!#:~1!"&if not defined # endlocal&exit/b %len%
goto :loop

:IsInteger value  ; returns %_OK% if integer, else %NotInteger%
if "%~1"=="" exit/b %NotInteger%
if %~1 gtr 9999 exit/b %NotInteger%
setlocal
set/a Integer=%_OK%
for /f "tokens=1* delims=0123456789" %%I IN ("%~1") do set "Integer=%%I"
if /i "%Integer%" neq "%_OK%" set/a Integer=%NotInteger%
endlocal&exit/b %Integer%

:Dec2ascii asciidecimal char
SetLocal
cmd /c exit /b %~1
endlocal&(call set %~2=^%=ExitCodeAscii%)&exit/b 0

:Timer milliseconds "Program"
if %~1 equ 0 goto :endT
setlocal enableextensions
set correct=0
set /a msecs=%~1+5
if /i %msecs% leq 20 set /a correct-=2
set time1=%time: =%
set /a tsecs=%1/1000 2>nul
set /a msecs=(%msecs% %% 1000)/10
for /f "tokens=1-4 delims=:." %%a in ("%time1%") do (
  set hour1=%%a&set min1=%%b&set sec1=%%c&set "mil1=%%d"
)
if /i %hour1:~0,1% equ 0 if /i "%hour1:~1%" neq "" set hour1=%hour1:~1%
if /i %min1:~0,1% equ 0 set min1=%min1:~1%
if /i %sec1:~0,1% equ 0 set sec1=%sec1:~1%
if /i %mil1:~0,1% equ 0 set mil1=%mil1:~1%
set /a sec1+=(%hour1%*3600)+(%min1%*60)
set /a msecs+=%mil1%
set /a tsecs+=(%sec1%+%msecs%/100)
set /a msecs=%msecs% %% 100
::check for midnight crossing
if /i %tsecs% geq 86400 set /a tsecs-=86400
set /a hour2=%tsecs% / 3600
set /a min2=(%tsecs%-(%hour2%*3600)) / 60
set /a sec2=(%tsecs%-(%hour2%*3600)) %% 60
set /a err=%msecs%
if /i %msecs% neq 0 set /a msecs+=%correct%
if /i 1%msecs% lss 20 set msecs=0%msecs%
if /i 1%min2% lss 20 set min2=0%min2%
if /i 1%sec2% lss 20 set sec2=0%sec2%
set time2=%hour2%:%min2%:%sec2%.%msecs%
:wait
  set timen=%time: =%
  %~2
  if !errorlevel! neq 0 exit/b !errorlevel!
  if /i %timen% geq %time2% goto :endT
goto :wait
:endT
exit/b %TimeOut%

set rtn=       !%%~B#$%%~A^&'^(^)*+,-./0123456789:;^<=^>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^^_`abcdefghijklmnopqrstuvwxyz{^|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
                           233                 4     4             6    6                        9       9                        1                     
                           723                 3     8=0           1=   5=A                      0=Z     7=a                      2
                                                                                                                                   2=z

:Create Getkey.exe from hex data
setlocal
set "inFile=%TEMP%\%~1.hex"
echo(4D5A900003[3]04[3]FFFF[2]B8[7]40[35]B0[3]0E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F74>%inFile%
echo(2062652072756E20696E20444F53206D6F64652E0D0D0A24[7]55B5B8FD11D4D6AE11D4D6AE11D4D6AE9FCBC5AE18D4D6AEED>>%inFile%
echo(F4C4AE13D4D6AE5269636811D4D6AE[8]5045[2]4C0102005A66D14F[8]E0000F010B01050C0002[3]02[7]10[3]10[3]20[4]40[2]10>>%inFile%
echo([3]02[2]04[7]04[8]30[3]02[6]03[5]10[2]10[4]10[2]10[6]10[11]1820[2]3C[84]20[2]18[27]2E74657874[3]96[4]10[3]02[3]02[14]20[2]602E>>%inFile%
echo(7264617461[2]BA[4]20[3]02[3]04[14]40[2]40[8]E806[3]50E873[3]E840[3]E85F[3]803E00741866813E2F57740766813E2F77740A>>%inFile%
echo(FF150C20400085C07419FF151020400085C074073DE0[3]7508FF1510204000F7D8C3CCCCCCCCE82F[3]8BF08A06463C227509>>%inFile%
echo(8A06463C2275F9EB0C8A06463C20740484C075F54EC38A06463C2074F94EC3CCFF2504204000FF2500204000FF2510204000FF>>%inFile%
echo(250C2040[363]7A20[2]6C20[6]A420[2]9A20[6]5420[10]8C20[3]20[2]6020[10]AE20[2]0C20[22]7A20[2]6C20[6]A420[2]9A20[6]9B004578>>%inFile%
echo(697450726F6365737300E600476574436F6D6D616E644C696E6541006B65726E656C33322E646C6C[2]CE005F6765746368[2]11 >>%inFile%
echo(015F6B62686974[2]6D73766372742E646C6C[328]>>%inFile%
if not exist "%inFile%" exit/b %GetKeyError%

set "Hexchar.Vbs=%TEMP%\Hexchar.vbs"
echo(Rem Hex digits to Ascii Characters conversion >%hexchar.vbs%
echo(Rem Antonio Perez Ayala - Apr/14/2012 >>%hexchar.vbs%
echo( >>%hexchar.vbs%
echo(Dim line,index,count>>%hexchar.vbs%
echo(line = WScript.StdIn.ReadLine^(^)>>%hexchar.vbs%
echo(While line ^<^> "">>%hexchar.vbs%
echo(   index = 1 >>%hexchar.vbs%
echo(   While index ^< len^(line^)>>%hexchar.vbs%
echo(      If Mid^(line,index,1^) = "[" Then>>%hexchar.vbs%
echo(         index = index+1>>%hexchar.vbs%
echo(         count = 0 >>%hexchar.vbs%
echo(         While Mid^(line,index+count,1^) ^<^> "]">>%hexchar.vbs%
echo(            count = count+1>>%hexchar.vbs%
echo(         WEnd>>%hexchar.vbs%
echo(         For i=1 To Int^(Mid^(line,index,count^)^)>>%hexchar.vbs%
echo(            WScript.StdOut.Write Chr^(0^)>>%hexchar.vbs%
echo(         Next>>%hexchar.vbs%
echo(         index = index+count+1 >>%hexchar.vbs%
echo(      Else>>%hexchar.vbs%
echo(         WScript.StdOut.Write Chr^(CByte^("&H"^&Mid^(line,index,2^)^)^)>>%hexchar.vbs%
echo(         index = index+2>>%hexchar.vbs%
echo(      End If>>%hexchar.vbs%
echo(   WEnd>>%hexchar.vbs%
echo(   line = WScript.StdIn.ReadLine^(^)>>%hexchar.vbs%
echo(WEnd>>%hexchar.vbs%
if not exist "%Hexchar.vbs%" exit/b %GetKeyError%

:: Convert *.exe.hex to binary *.exe
set "outFile=%temp%\%~1"
Cscript /Nologo /B /E:VBS %HexChar.vbs% < "%inFile%" > "%outFile%"
if exist "%outFile%" (set err=%_OK%) else (set err=%GetKeyError%)
del %HexChar.vbs% >nul 2>&1
del %inFile% >nul 2>&1
endlocal&(if %err% equ 0 call set "%~1=%outFile%")&exit/b %err%


penpen
Expert
Posts: 2009
Joined: 23 Jun 2013 06:15
Location: Germany

Re: Need help with parameter arguments

#9 Post by penpen » 25 Jun 2014 12:00

Adrianvdh wrote:But I have another question. How would I have a rule set?

Where '/r /c /n' can only work together and '/u /d' can only also work together..

for example:
comandline: "C:\file.bat /r /u"

Code: Select all

echo The syntax of the command is incorrect.

You could use something like this:

Code: Select all

@echo off
setlocal
set "/r="&set "/u="&set "/c="&set "/d="&set "/n="
if not "%~1"=="" (
   if "%~1"=="/?" goto ListPar
   for %%a in (%*) do (
      if "%%~a"=="/r" set "/r=true"
      if "%%~a"=="/u" set "/u=true"
      if "%%~a"=="/c" set "/c=true"
      if "%%~a"=="/d" set "/d=true"
      if "%%~a"=="/n" set "/n=true"
   )
)
if defined /r echo r
if defined /u echo u
if defined /c echo c
if defined /d echo d
if defined /n echo n

if not "%/r%%/u%%/c%" == "" if not "%/u%%/d%" == "" (
   echo The syntax of the command is incorrect.
   exit /b 1
)

endlocal
goto :eof

penpen

Post Reply