1

I want the program to process an arbitrary number of command-line arguments, but I'm unsure how to implement a for loop to go through multiple shift commands. Also, the program shouldn't close the command prompt window when it ends.

Here is what I have so far:

@echo off
if "%1"=="" goto skip
if "%1"=="-ti" time /t
if "%1"=="-da" date /t
if "%1"=="-c" cls
if "%1"=="-ip" ipconfig
if "%1"=="-d" dir
if "%1"=="-p" path
if "%1"=="-v" ver
if "%1"=="-t" type
if "%1"=="-m" md
exit /b
:skip
echo No arguments!

I'd like to have the following command-line arguments run properly:

C:\>batchfile –d –ti –da –ip –v
C:\>batchfile
C:\>batchfile –d –m CSC3323 –d
C:\>batchfile –d –t batchfile.bat –m CSC3323 –d
JosefZ
  • 28,460
  • 5
  • 44
  • 83
John
  • 23
  • 3
  • 2
    Possible duplicate of [Batch file for loop through switch-like arguments?](http://stackoverflow.com/questions/5247636/batch-file-for-loop-through-switch-like-arguments) – wOxxOm Nov 24 '15 at 18:49
  • This is hard to do in Cmd.exe shell script (batch file) code. I would strongly recommend PowerShell, which has fancy parameter parsing built right in. This article will give you an introduction - [Windows IT Pro - PowerShell: Why You'll Never Go Back to Cmd.exe Batch Files](http://windowsitpro.com/windows/powershell-why-youll-never-go-back-cmdexe-batch-files). – Bill_Stewart Nov 24 '15 at 18:50

1 Answers1

2

Use this code to loop through your arguments in a file called batchfile.bat:

@echo off
echo arguments: "%*"
:loop
if "%~1"=="" goto skip
if "%~1"=="-ti" time /t
if "%~1"=="-da" date /t
if "%~1"=="-c" cls
if "%~1"=="-ip" ipconfig
if "%~1"=="-d" dir
if "%~1"=="-p" path
if "%~1"=="-v" ver
if "%~1"=="-t" type
if "%~1"=="-m" md
shift
goto loop
:skip
echo No arguments!
pause

and call the batchscript like this:

start batchfile.bat -ti -d -ti -da -ip -v 
start batchfile.bat
start batchfile.bat -d -m CSC3323 -d 
start batchfile.bat -d -t batchfile.bat -m CSC3323 -d 
Dennis van Gils
  • 3,487
  • 2
  • 14
  • 35