Thejesh PR
Thejesh PR

Reputation: 1075

How to apply for loop for comma separated arguments passed to the script in batch?

I have a list of folders listed below:

I have to pass comma separated arguments to scripts like given below:

script.bat C:\Program Files,C:\temp,C:\John Snow

After passing to the script I need to filter out comma separated argument and apply for each loop and echo the argument value and execute dir command to list files in that director

Upvotes: 1

Views: 343

Answers (2)

JosefZ
JosefZ

Reputation: 30113

@ECHO OFF
SETLOCAL EnableExtensions
set "_params=%*"
if not defined _params (
  echo %~nx0: nothing to do
  pause
  exit /B
)
set "_params=%_params:,=","%"
for %%G in ("%_params%") do (
  echo dir "%%~G"
)

Output

==> 37321331.bat
37321331.bat: nothing to do
Press any key to continue . . .

==> 37321331.bat C:\Program Files,C:\temp,C:\John Snow
dir "C:\Program Files"
dir "C:\temp"
dir "C:\John Snow"

==>

Above script requires some elaborating: it would fail if some argument is enclosed in a pair of double quotes:

==> 37321331.bat C:\Program Files,C:\temp,"C:\John Snow"
dir "C:\Program Files"
dir "C:\temp"
dir ""C:\John"
dir "Snow"""

Edit. Use next code snippet to fix it: set "_params=%_params:"=%" would remove all " double quotes from supplied string.

set "_params=%_params:"=%"
set "_params=%_params:,=","%"
for %%G in ("%_params%") do (
  echo dir "%%~G"
)

Resources (required reading, incomplete):

Upvotes: 1

npocmaka
npocmaka

Reputation: 57252

set "args=%*"
set "args=%args:,=","%"
for %%# in ("%args%") do (
  dir "%%~#"
)

try this.

Upvotes: 0

Related Questions