You have found this blog post because you are wondering if there is a way to express a “switch/case” logic in Batch files.
The short answer is: “no, not exactly”. However, there are ways to achieve the same in Batch files.
In the Batchography book, I explain in details the “switch/case” construct, but in this blog post I will illustrate this mechanism briefly. For more advanced Batch scripting topics, please grab a copy of the Batchography book.
Get the book from Amazon:
There is no built-in “switch/case” syntax in the Batch files scripting language, however we can achieve that with environment variables and the GOTO or the CALL syntax.
Consider the following C code and see how to express something similar in the Batch files language:
switch (n) { default: printf("Something else\n"); break; case 1: printf("One\n"); break; case 2: printf("Two\n"); break; case 3: printf("Three\n"); break; } printf("After Switch/case");
In the Batch files scripting language, we can use the GOTO keyword to jump to a dynamically generated label name:
@echo off echo Switch/case in Batch script set /P N=Enter switch case number: :switch-case-example :: Call and mask out invalid call targets goto :switch-case-N-%N% 2>nul || ( :: Default case echo Something else ) goto :switch-case-end :switch-case-N-1 echo One goto :switch-case-end :switch-case-N-2 echo Two goto :switch-case-end :switch-case-N-3 echo Three goto :switch-case-end :switch-case-end echo After Switch/case
Please refer to the Batchography book for a more detailed explanation on the switch/case topic and other Batch scripting topics.
You might also like:
- Batchography: How to do string substitution in the Batch scripting language?
- Batchography: Embedding an executable file in a Batch script
- Batchography: How to check if your Batch file script is running as an Administrator
- WifiPasswordReveal: A script to reveal all the saved WiFi passwords in Windows 7 and above
- Free pictures to PDF converter: Pic2Pdf v1.0
- Introducing the “Batchography: The Art of Batch Files Programming” book