- Overview
- Part 1 – Getting Started
- Part 2 – Variables
- Part 3 – Return Codes
- Part 4 – stdin, stdout, stderr
- Part 5 – If/Then Conditionals
- Part 6 – Loops
- Part 7 – Functions
- Part 8 – Parsing Input
- Part 9 – Logging
- Part 10 – Advanced Tricks
Robust parsing of command line input separates a good script from a great script. I’ll share some tips on how I parse input.
The Easy Way to read Command Line Arguments
By far the easiest way to parse command line arguments is to read required arguments by ordinal position.
Here we get the full path to a local file passed as the first argument. We write an error message to stderr if the file does not exist and exit our script:
SET filepath=%~f1
IF NOT EXIST "%filepath%" (
ECHO %~n0: file not found - %filepath% >&2
EXIT /B 1
)
Optional parameters
I assign a default value for parameters as such
SET filepath=%dp0\default.txt
:: the first parameter is an optional filepath
IF EXIST "%~f1" SET filepath=%~f1
Switches
Named Parameters
Variable Number of Arguments
Reading user input
:confirm
SET /P "Continue [y/n]>" %confirm%
FINDSTR /I "^(y|n|yes|no)$" > NUL || GOTO: confirm