0

Within a Windows Batch script, how can I check if a given parameter is set in any position? For example, say I called myscript.bat, as follows:

myscript.bat /foo /bar

I want to determine if /foo is set I could do:

if "%1" == "/foo" echo "/foo is set"

But say now I call the script as follows:

myscript.bat /bar /foo

The above code no longer echos /foo is set.

How can I write an if condition such that is true whether /foo is in any position? Does Windows Batch provide a simple way of doing this without having to check every parameter in a for loop?

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Dan Stevens
  • 6,392
  • 10
  • 49
  • 68
  • I may be able to do this by using a substring search against all the parameters using `%*` and the techniques described in https://stackoverflow.com/questions/7005951/batch-file-find-if-substring-is-in-string-not-in-a-file – Dan Stevens Jul 07 '21 at 09:21
  • 1
    Considering your rep score and that you're not a new member, I was wondering why your question shows no effort at having tackled the issue yourself. I'm also interested to know why you have limited advice to solutions using `If` and not using `For`. – Compo Jul 07 '21 at 11:48
  • 1
    Take a look at the tread [Using parameters in batch files at Windows command line](https://stackoverflow.com/q/14286457), particularly the [accepted answer](https://stackoverflow.com/a/14298769), to learn about a possible way to solve your issue… – aschipfl Jul 07 '21 at 14:17

2 Answers2

1

There are several ways to do this. Perhaps this is the simplest one:

@echo off
setlocal

rem Set elements of "argv" array variable
for %%a in (%*) do set "argv[%%a]=1"

rem Check for a given switch
if defined argv[/foo] echo /foo is set

You may extend this method in this way:

@echo off
setlocal

rem Set elements of "argv" array variable
set "n=0"
for %%a in (%*) do set /A "n+=1, argv[%%a]=n"

rem Check for a given switch and its position
if defined argv[/foo] echo /foo is set at position %argv[/foo]%
Aacini
  • 65,180
  • 12
  • 72
  • 108
0

You should give a real example of why you need to get confirmation of the argument.

However this not so good example will work after a fashion without for and one if

@echo off & set foo=
echo "%*" | find "/foo" && set foo=found
if "%foo%" equ "found" echo "/foo is set"
K J
  • 8,045
  • 3
  • 14
  • 36