Passing command-line arguments to a windows batch script
I need to create a windows batch script where I need to pass a few command-line arguments. These arguments may appear in in any order, but the script should pick them up properly based on the argument name. E.g.:
<scriptname> -age <agevalue> -gender <gender>
<scriptname> -gender <gender> -age <agevalue>
The script can be called in any of the two above ways but the age and gender should be properly picked up and assigned to variables. The arguments can be identified by the switch before them - i.e., -age , -gender, etc.
Can someone please give me an example of identifying this internally ?
batch, unfortunately, doesn't have a builtin getops
function like bash does. However, you could implement your own poor-man's variant:
:GETOPTS
if /I %~1 == --age set AGE=%2& shift
if /I %~1 == --gender set GENDER=%2& shift
shift
if not (%1)==() goto GETOPTS
Can you do it with Powershell? or does it need to be batch? Powershell makes it nice and easy, you just need to add something like this at the top of your script, and then you can call each parameter in any order
param (
[string]$Age,
[string]$Gender
)
You can do it with batch, but it will require lots of parameter checking.. Here's a few links of some batch scripts that do it
http://www.ericphelps.com/batch/samples/arguments.bat.txt
(Possible dupplicate of)
https://stackoverflow.com/questions/5215729/is-there-a-way-to-pass-parameters-by-name-and-not-by-order-to-a-batch-bat-f