15 Useful Batch files programming recipes

In the Batchography book, I cover basic to advanced Batch files programming topics. Since the book was published in 2016, I kept blogging about Batch programming language.

Here’s a collection of some useful recipes:

  1. Check if the script is running as an Administrator
  2. String substitution
  3. Number counting
  4. Batch files and Unicode
  5. Read from a text file, one line at a time
  6. Switch/case in Batch files
  7. Auto reinterpret/compile changed files
  8. Reading from a file
  9. Tokenizing command output
  10. Polyglot: Python and Batch files
  11. Polyglot: Batch file + self compiling C++
  12. Embedding binaries inside Batch files
  13. Interactive Batch files
  14. Writing a game – The Hangman
  15. Batchography: Parsing INI files from a Batch file

 

flower separator
batchography-good-resDo you want to master Batch Files programming? Look no further, the Batchography is the right book for you.

Available in print or e-book editions from Amazon.

flower separator


flower separator

You might also like:

Batchography: Detect Windows Language

To detect the Windows Operating system language, it is enough to query the registry. We use the “reg query” command and then parse the output.

@echo off

setlocal

:: https://docs.microsoft.com/en-us/previous-versions/office/developer/speech-technologies/hh361638(v=office.14)

for /F "usebackq tokens=3" %%a IN (`reg query "hklm\system\controlset001\control\nls\language" /v Installlanguage`) DO (
  set lang_id=%%a
)
:: 0409 English ; 0407 German ; 040C French ; 0C0A Spanish

if "%lang_id%"=="0409" (
  echo English detected
) else if "%lang_id%" == "040C" (
  echo French detected
) else (
  echo Note: Unknown language ID %lang_id%!
)

echo LangID=%lang_id%

You can learn about advanced Batch scripting techniques in the Batchography book.
flower separator
batchography-good-resDo you want to master Batch Files programming? Look no further, the Batchography is the best book on the topic and the most up to date!

Available in print or e-book editions from Amazon.

 


You might also like:

Batchography: what happens when you redirect ‘cls’ to a file?

Let’s assume you have a Batch file (test.bat) with the following contents:

@echo off
echo 1
cls
echo 2

And then you run this Batch file and redirect its output to a text file called “out.txt”:

C:>test.bat >out.txt

What do you think the output would be?

At first, I thought it would be:

1
2

But little did I know that when ‘cls’ is invoked in a context where stdout is redirect to a file, then a form feed character (0xC) is emitted instead:

I was curious, so I disassembled ‘cmd.exe’ to verify my findings. Lo and behold, indeed, ‘cmd.exe’ does that:

int __stdcall eCls(struct cmdnode *a1)
{
  HANDLE hStdOut;
  HANDLE v2;
  SMALL_RECT ScrollRectangle; 
  COORD dwDestinationOrigin;
  CHAR_INFO Fill;
  struct _CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo;

  if ( FileIsDevice((char *)1) )
  {
    hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    if ( GetConsoleScreenBufferInfo(hStdOut, &ConsoleScreenBufferInfo) )
    {
      dwDestinationOrigin.Y = -ConsoleScreenBufferInfo.dwSize.Y;
      dwDestinationOrigin.X = 0;
      *(_DWORD *)&ScrollRectangle.Left = 0;
      ScrollRectangle.Bottom = ConsoleScreenBufferInfo.dwSize.Y;
      ScrollRectangle.Right = ConsoleScreenBufferInfo.dwSize.X;
      Fill.Char.UnicodeChar = 32;
      Fill.Attributes = ConsoleScreenBufferInfo.wAttributes;
      ScrollConsoleScreenBufferW(hStdOut, &ScrollRectangle, 0, dwDestinationOrigin, &Fill);
      ConsoleScreenBufferInfo.dwCursorPosition = 0;
      v2 = GetStdHandle(0xFFFFFFF5);
      SetConsoleCursorPosition(v2, 0);
    }
    else
    {
      cmd_printf(page_feed);
    }
  }
  else
  {
    cmd_printf(page_feed);
  }
  return 0;
}

(Lines 29 and 34 are of interest)

In conclusion, be aware if you redirect a Batch file to another file and compare the result. If the Batch file uses CLS, you have to account for the form feed character showing up!
flower separator
batchography-good-resDo you want to master Batch Files programming? Look no further, the Batchography is the best book on the topic and the most up to date!

Available in print or e-book editions from Amazon.

 


You might also like:

 

Batchography: Batch script to automatically recompile or run a script interpreter

Hello,

In a previous blog post, I showed you how to write a polyglot Batch file that is both a Batch script and a C++ source file. When the Batch file is executed, it compiles itself (as C++).  In this blog post I am going to show you how to write a Batch file script that polls the file system periodically to see if a given input file is changed and if so, it will invoke the compiler or interpreter of your choice.

This concept is similar to what the Compiler Explorer does actually.

I am going to write a small script that keeps running your Python script automatically in a separate console window the moment you save the script in your editor. Check the script in action:

Continue reading “Batchography: Batch script to automatically recompile or run a script interpreter”

Batchography: Parsing INI files from a Batch file

Often times you might want to write Batch file scripts to automate system administration tasks, and in addition to that you might want to pass configuration files to your Batch scripts.

This article, inspired by the Batchography book, shows you how to parse INI files and retrieve values from a given section and key.

Quick background

An INI file (or initialization file) is a text file that has the following format:

; comment

[section_name1]
Key1Name=Value1
.
.
.
[section_name2]
Key1Name=Value1
Key2Name=Value2
.
.
.

In the MS Windows operating system, a C/C++ programmer can read/write values from the INI files using the following APIs:

But can we do the same using Batch files?

Yes and in the next section, we show you how to read values from the INI file. Continue reading “Batchography: Parsing INI files from a Batch file”

Batchography: Autorun a Batch file script each time you open the command prompt

This is yet another short article from the many topics mentioned in the Batchography book. In this article, I am going to show you how to have a Batch file of your choice execute each time you open the command prompt.

Putting it simply, all you have to do is create a string registry value called AutoRun under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command then specify the path of the Batch script you want to run!

A useful AutoRun Batch script is a script that sets up command macros using the Doskey command, but that’s a topic for another time!
flower separator
Buy from Amazon:

Batchography: Arithmetic operations in Batch files

Did you know that you can do basic arithmetic operations in a Batch file script?

The syntax is simple:

set /A result=EXPR

For example, to add 10 and 20:

@echo off
set /p result=10+20
echo result=%result%

From the “SET /?” output, these are the supported arithmetic operations:

The /A switch specifies that the string to the right of the equal sign
is a numerical expression that is evaluated.  The expression evaluator
is pretty simple and supports the following operations, in decreasing
order of precedence:

    ()                  - grouping
    ! ~ -               - unary operators
    * / %               - arithmetic operators
    + -                 - arithmetic operators
    << >>               - logical shift
    &                   - bitwise and
    ^                   - bitwise exclusive or
    |                   - bitwise or
    = *= /= %= += -=    - assignment
      &= ^= |= <<= >>=
    ,                   - expression separator

Now, let’s make a simple interactive calculator:

@echo off
:main
  setlocal
  set /p num1=Enter first number:
  set /p op=Enter operator:
  set /p num2=Enter second number:

  set /a result=%num1% %op% %num2%

  echo Result is %result%

  endlocal

  goto :eof

When we enter: 4, * then 5, we get the following output:

Enter first number:4
Enter operator:*
Enter second number:5
Result is 20

The Batchography book covers this topic in details and more. Check it out!

You might also like:

Batchography: Function calls in Batch file scripts

The Batch files programming language is a powerful language but unfortunately, not many people know it that well. In an effort to pass the knowledge, in this article I am going to illustrate how to do function calls in Batch scripts.

Let’s get started!

The basics

The following example illustrates how to define and call a function:

@echo off
:main
  call :hello
  call :world
  goto :eof

:hello
  echo This is the Hello function
  goto :eof

:world
  echo This is a second function call
  goto :eof

The following outputs:

This is the Hello function
This is a second function call

From the example above, it is obvious how to call a function and return from it:

  1. Define a function as you would define a label
  2. Use the “CALL :function-name” syntax to call the function
  3. Use the “GOTO :EOF” to return from the function back to the caller

Recursive functions are also supported in the Batch language. Just make sure you avoid infinite recursion. Continue reading “Batchography: Function calls in Batch file scripts”

Batchography: Polyglot Batch files and C++ – Self compiling C++ script

This article is part of the Batchography articles series and today, I am going to show you how to write a valid Batch file that is also a valid C/C++ file. The Batch file part of the source can do anything, however in this article, its sole purpose will be to compile itself and run the compile C++ program.

Let’s get started with the Polyglot source code:

Continue reading “Batchography: Polyglot Batch files and C++ – Self compiling C++ script”

Batchography: Batch files and Unicode

Recently, I had to update my popular utility that resets NTFS files permission to support Unicode paths. I had to investigate how to add Unicode support in Batch scripts. It seems that this was a topic I forgot to add into my comprehensive Batch files programming book.

This article is the result of my investigation, in which I am going to show you how to add Unicode support to your Batch file scripts in 3 easy steps.

Continue reading “Batchography: Batch files and Unicode”

Batchography: Embedding Python scripts in your Batch file script

I keep writing about Batch programming, so it is obvious by now that Batch files programming has become one of my favorite activities. Every time I have to write a quick script to automate a task, I go first for the Batch files programming language. If that does not do the job, I use the Python programming language and if that fails, I go for C/C++ before deciding to writing using the assembly language.

Now, what about combining the two languages to achieve what you want?

That’s today’s topic. It is an excerpt from Chapter 4 in the Batchography book. Continue reading “Batchography: Embedding Python scripts in your Batch file script”

Batchography: Reading a text file line by line in Batch files

This is yet another article about Batch files. In this article, I am going to show you how to read a text file line by line using the Batch files scripting language.

For more advanced Batch scripting topics, please grab a copy of the Batchography book.

batchography-good-res

Let’s get started! Continue reading “Batchography: Reading a text file line by line in Batch files”

Batchography: Converting numbers to characters (or the CHR() function)

In various programming languages, you might sometimes need to convert numbers to characters. In simple terms, each character you see has a numerical representation. The ASCII table  shows the numbers of each character and its corresponding glyph.

Converting numbers to their corresponding characters would be useful to generate a random string for instance. The first step to generating a random string is to generate random numbers between 65 and 90 (upper case ‘A’ to upper case ‘Z’) or between 97 and 122 (lower case ‘a’ to lower case ‘z’).

While the Batch language is pretty primitive, you would be surprised how many things you can do with it. In the Batchography book, I cover various topics that would bring your Batch programming skills to the next level.
batchography-good-res

Get the book from Amazon:

  • Paperback editionbtn-buy-on-amazon
  • E-book editionbtn-buy-on-amazon

flower separator Continue reading “Batchography: Converting numbers to characters (or the CHR() function)”

Batchography: How to do a “switch/case” in Batch files

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.

batchography-good-res

Get the book from Amazon:

  • Paperback editionbtn-buy-on-amazon
  • E-book editionbtn-buy-on-amazon

flower separator Continue reading “Batchography: How to do a “switch/case” in Batch files”

Batchography: How to do string substitution in the Batch scripting language?

There are so many undocumented or obscure features in the Batch scripting language and in this article I am going to illustrate how to do string substitution.

For more advanced Batch scripting topics, please grab a copy of the Batchography book.

batchography-good-res

Let’s get started! Continue reading “Batchography: How to do string substitution in the Batch scripting language?”

Batchography – Programming the “Hangman game” using the Batch scripting language!

hangman-1In this blog post, I am going to share with you the high level steps needed to build the Hangman game using the Batch scripting language.

To learn more about how the Hangman is programmed using the Batch scripting language, please refer to Chapter 5 in the Batchography book.

flower separator
batchography-good-res
Get the book from Amazon:

  • the print editionbtn-buy-on-amazon
  • or the e-book editionbtn-buy-on-amazon

flower separator

Continue reading “Batchography – Programming the “Hangman game” using the Batch scripting language!”