/* steve jansen */

// another day in paradise hacking code and more

Windows Batch Scripting: Parsing Input

| Comments

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

<< Part 7 – Functions Part 9 – Logging >>

Comments