- /* steve jansen */
- // another day in paradise hacking code and more
- Guide to Windows Batch Scripting
- Why Windows?
- Why DOS-style Batch Files?
- Series Parts
- Comments
- Guides
- Recent Posts
- Social Stuff
- Batch file – Programming tutorial
- Batch File Programming tutorial
- Batch File Programming – Introduction
- How to create a batch file?
- How to run a batch file?
- Explanation of the program
- Batch File Programming – DOs and DON’Ts
- Some final words of advice before you start playing around batch commands
- Using parameters in batch files at Windows command line
- 5 Answers 5
- Checking if a parameter was passed
- Handling more than 9 arguments (or just making life easier)
- Substitution of batch parameters
- How to create and run batch file on Windows 10
- How to create a batch file on Windows 10
- Create basic batch file
- Create advanced batch file
- Create actionable batch file
- How to run a batch file on Windows 10
- Run batch file on-demand
- Command Prompt
- File Explorer
- Run batch file on schedule
- Run batch files on startup
- More Windows 10 resources
- Add the best VR headset to your Microsoft Flight Simulator experience
- The Dell XPS 15 is our choice for best 15-inch laptop
- Halo: MCC’s live service elements make it better, not worse
- These are the best PC sticks when you’re on the move
/* steve jansen */
// another day in paradise hacking code and more
Guide to Windows Batch Scripting
I love shell scripting – it’s the duct tape of programming to me. Low cost, high benefit. And it feels like art, where one can learn to do increasingly complex tasks with greater simplicity.
Sadly, I feel like it’s a developer skill on the decline. Maybe new developers feel it’s “not real programming”. Perhaps the growing dominance of Java as the lingua franca of academic comp sci courses has made shell scripting less relevant in university settings.
True, shell scripting feel a bit “vocational”, maybe even a bit unsexy compared to Python/Ruby/LISP/blah/blah/blah. Nevertheless, it’s a skill that becomes invaluable as you gain seniority and start doing more DevOps in you day job, or if you want to do some high-speed, low drag stuff to tailor your development environment like this.
Why Windows?
This series will share some of the tips and tricks I’ve picked up through the years of working with Windows professionally. I’ll be the first to admit the Unix shells of the world are far superior to the Windows command prompt (or even Windows PowerShell). Windows is a fact of life for most professionals writing code for coporate customers; this series aims to make life with Windows a little easier.
Why DOS-style Batch Files?
This series will share some conventions I picked up along the way for scripting in Windows via command prompt batch files. The Windows PowerShell is definitely sweet, but, I still like batch files for their portability and low friction. The Windows command line is very stable – no worrying about the PowerShell interpreter path, which version of PowerShell the server is running, etc.
Series Parts
Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows
Comments
Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.
And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.
Guides
Recent Posts
Social Stuff
- @steve-jansen on GitHub
- @steve-jansen on StackOverflow
- @steve-jansen ProTips on Coderwall
- @steve-jansen on Microsft Connect
- @steve-jansen on ASP.NET User Voice
- Subscribe via RSS
Copyright © 2015 — Steve Jansen — Powered by Octopress
Batch file – Programming tutorial
Many of us have heard or perhaps known about the batch file, but very few are aware of its power and dominance in Windows. Almost everything can be done when we know relevant command line instructions. So in this series of tutorials, we will learn about batch file programming and how we can execute command line instructions with a single click through them.
Batch File Programming tutorial
Batch File Programming – Introduction
A batch file is an unformatted text file or script file which contains multiple commands to achieve a certain task. It contains series of command that is executed by command line interpreter.
Extensions: .bat or .cmd
The instructions in batch files are for automating repetitive command sequences.
Before the implementation of modern GUI’s ( Graphical User Interface ), in the operating system like MS-DOS, we had to operate every command from command line. Even though we are facilitated with GUI’s, many major core operations can only be achieved through command line instructions.
So whenever we write instructions or codes in batch files, we are executing command line operations through our instructions and when we know how to write commands, we can do many powerful things in the Windows.
For example: We can create a .bat file with instructions of shutting down and whenever clicked in that file, Windows will automatically shut down.
Sounds fun, right?
How to create a batch file?
Well as simple as it sounds, you don’t need any extra software installed to create a batch file.
Just open up a built-in text editor for windows.
After writing commands, all you need to do is save it as a .bat or .cmd file.
Voila, you have created your first ever batch file. But you haven’t put any instructions. We will cover about programming and scripting in next articles.
Now that you know how to create a batch file, you must be wondering how to run it?
How to run a batch file?
It may sound funny, but all you have to do is click that file to run it and Windows will automatically run the commands written in a batch file.
A batch file can also be run via command prompt. In order to execute the batch file from command prompt, we must set the path to the directory where the batch file is stored or we should include the path address to that directory.
Let’s create a simple batch script to display “This is my first script”.
- First, open up a text editor and save the file as a .bat file
- Copy and paste the code above and click on that file to run the script
It will generate an output like this.
Explanation of the program
Line 1:
If we don’t put @echo off at the top of the script, it will produce an output where ‘echo’ itself will also be displayed. And the output becomes like:
So to avoid the display of command itself, we must use @echo off at the top.
Line 2:
Line 2 just echoes ‘This is my first script’ onto the console.
Line 3: Pause is used to hold the screen until we press a key. If pause is not used, the output screen will vanish away within a blink of an eye and we won’t be able to see the output.
Batch File Programming – DOs and DON’Ts
You must always follow best programming practice while writing codes, be it batch file programming or any.
Even in short programs, we must maintain the habit of following better practice because while we write huge programs, it becomes a nightmare to debug it and also maintain it because no one else will understand your code if not properly documented.
So here are the few things that must be implemented and few things that must be avoided while coding.
DOs
- Documenting code with comments
Perhaps this is one of the most important one because without proper documentation it becomes tedious to maintain the code and debug it .
So it is always a good idea to insert comments in programs or codes, explaining what the next lines or block of code is trying to accomplish, how and why.
Either REM or : : is used for comments in batch file programming. Here is the example.
As simple as it is to code batch files, so is to hack and tweak the code because everything is like plain English in batch programs. Batch files are weakly typed, so it is always a better approach to validate all the inputs in batch file programming.
Always check the new variable before using them or initializing them because they might already have been defined.
Without proper indentation, a program becomes confusing to intercept. So always use proper indentation in every line of code for better understanding of the code.
DON’Ts
If there are few things to be considered for better programming practice, there are also certain things that must be avoided. Here are the few things that you as a programmer should try to avoid while coding.
- Avoid one-liner codes (multiple command lines joined into a single one by ANDs and ORs) and use a block of code.
- Avoid nested block codes (nested if else) and use subroutines instead.
- Don’t use variable names as command names
Some final words of advice before you start playing around batch commands
Now that you have known about the batch files, in the coming tutorials, you will learn about advanced concepts in batch file programming.
But we should warn you that, batch file commands and scripts are too much powerful and if used without proper knowledge, it can crash your machine and software’s functionalities. Make sure you know what you are doing because with batch scripts we are playing with the core feature of Windows.
Using parameters in batch files at Windows command line
In Windows, how do you access arguments passed when a batch file is run?
For example, let’s say I have a program named hello.bat . When I enter hello -a at a Windows command line, how do I let my program know that -a was passed in as an argument?
5 Answers 5
As others have already said, parameters passed through the command line can be accessed in batch files with the notation %1 to %9 . There are also two other tokens that you can use:
- %0 is the executable (batch file) name as specified in the command line.
- %* is all parameters specified in the command line — this is very useful if you want to forward the parameters to another program.
There are also lots of important techniques to be aware of in addition to simply how to access the parameters.
Checking if a parameter was passed
This is done with constructs like IF «%
1″==»» , which is true if and only if no arguments were passed at all. Note the tilde character which causes any surrounding quotes to be removed from the value of %1 ; without a tilde you will get unexpected results if that value includes double quotes, including the possibility of syntax errors.
Handling more than 9 arguments (or just making life easier)
If you need to access more than 9 arguments you have to use the command SHIFT . This command shifts the values of all arguments one place, so that %0 takes the value of %1 , %1 takes the value of %2 , etc. %9 takes the value of the tenth argument (if one is present), which was not available through any variable before calling SHIFT (enter command SHIFT /? for more options).
SHIFT is also useful when you want to easily process parameters without requiring that they are presented in a specific order. For example, a script may recognize the flags -a and -b in any order. A good way to parse the command line in such cases is
This scheme allows you to parse pretty complex command lines without going insane.
Substitution of batch parameters
For parameters that represent file names the shell provides lots of functionality related to working with files that is not accessible in any other way. This functionality is accessed with constructs that begin with %
For example, to get the size of the file passed in as an argument use
To get the path of the directory where the batch file was launched from (very useful!) you can use
You can view the full range of these capabilities by typing CALL /? in the command prompt.
How to create and run batch file on Windows 10
Source: Windows Central
On Windows 10, a batch file is a special text file that typically has a .bat extension, and it includes one or more commands that Command Prompt can understand and run in sequence to perform various actions.
Usually, you can type commands manually to perform a particular task or change system settings on Windows 10. However, a batch file simplifies the work of retyping commands, saving you time and potentially irreversible mistakes.
You can also use other tools like PowerShell to write even more advanced scripts. However, using batch files with Command Prompt is a convenient option when you need to run commands to change settings, automate routines, and start apps or launch websites.
In this Windows 10 guide, we’ll walk you through the steps to create and run your first batch file on your device. Also, we’ll outline the steps to create advanced scripts and automate scripts using the Task Scheduler.
How to create a batch file on Windows 10
The process of creating a batch (script or batch script) file is simple. You only need a text editor and some basic knowledge typing Command Prompt native commands. In the instructions below, we’ll outline the steps for writing a basic and advanced batch file, as well as the steps to write a script to change the system settings on Windows 10.
Create basic batch file
To create a basic batch file on Windows 10, use these steps:
- Open Start.
- Search for Notepad and click the top result to open the app.
Type the following lines in the text file to create a batch file:
Source: Windows Central
The above script outputs the phrase, «Congratulations! Your first batch file executed successfully» on the terminal screen.
Source: Windows Central
- @ECHO OFF — Disables the display prompt to show only the message on a clean line. Usually, this line goes at the beginning of the file. (You can use this command without «@,» but the symbol hides the command being executed to create a cleaner return.)
- ECHO — Prints any text on the screen.
- PAUSE — Keeps the window open after executing the command. If you don’t use this command, the window will close automatically as soon as the script finishes running. You can use this command at the end of the script or after a specific command when running multiple tasks, and you want to pause between them.
Type a name for the script — for example, first_basic_batch.bat.
Quick note: While batch files typically use the .bat file extensions, you can also find scripts using the .cmd or .btm file extensions.
Once you complete the steps, you can double-click the file to run it, or you can use the steps below to learn the different ways to execute a batch file on Windows 10.
Create advanced batch file
To create an advanced batch file to execute multiple commands, use these steps:
- Open Start.
- Search for Notepad and click the top result to open the app.
Type the following lines in the text file to create a more advanced batch file:
Source: Windows Central
The above script runs a series of commands to query different system information. Then it groups them into three different categories, including «WINDOWS INFO,» «HARDWARE INFO,» and «NETWORK INFO.» The «start» command will also open a Microsoft support website listing the official Windows 10 system requirements on your default web browser, which you can check against your information.
Source: Windows Central
- @ECHO OFF — Disables the display prompt to show only the message on a clean line. Usually, this line goes at the beginning of the file. (You can use this command without «@,» but the symbol hides the command being executed for a cleaner return.)
- TITLE — Displays a custom name in the title bar of the window.
- :: — Allows you to write comments and documentation information. These details are ignored when the batch file runs.
- ECHO — Prints the exact text on the screen.
- START — Lets you launch an app or website with the default web browser.
- PAUSE — Keeps the window open after executing the command. If you don’t use this command, the window will close automatically as soon as the script finishes running. You can use this command at the end of the script or after a specific command when running multiple tasks, and you want to pause between them.
After you complete the steps, double-click the .bat file to run it, or you can use the steps below to learn the different ways to run a batch.
Create actionable batch file
In addition to executing and displaying content in a Command Prompt window, you can also write non-interactive batch scripts to perform virtually any task you need.
To create a batch file that runs a specific command without user interaction, use these steps:
- Open Start.
- Search for Notepad and click the top result to open the app.
Copy and paste the following command in the text file:
Source: Windows Central
Quick note: In the screenshot, you’ll notice the «pause» command, but it’s not required. It was added in this example to take a screenshot of the terminal. If you’re accessing the files from another computer that uses a specific username and password, don’t forget to use the /user: option with the necessary credentials.
The above script includes a simple command to map a network folder as a drive inside File Explorer using the «Z» drive letter.
Source: Windows Central
Once you complete the steps, the batch file will map the network folder with the specified settings without opening a Command Prompt window. While we only used one command in this particular file, you can include as many commands as you like, as long as you write them one per line.
How to run a batch file on Windows 10
On Windows 10, you can run a batch file in at least three ways. You can run it on-demand using File Explorer or Command Prompt. You can create a task with Task Scheduler to run it on schedule. Or you can place the script in the «Startup» folder to run it every time you sign in to your Windows 10 account.
Run batch file on-demand
If you need to run a script on-demand, you have two choices, including Command Prompt or File Explorer.
Command Prompt
To run a batch file with Command Prompt, use these steps.
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
Type the path and name of the batch file, and press Enter:
For example, the following command runs the batch file located in the «scripts» folder, inside the «Downloads» folder:
Source: Windows Central
After you complete the steps, the console will return the results, and the window won’t close even if the script doesn’t include the «PAUSE» command.
File Explorer
To run a batch file with File Explorer, use these steps:
- Open File Explorer.
- Browse to the folder with the script.
- Double-click the batch file to run it.
(Optional) If you execute a command that requires administrator privileges, you’ll need to run the script as an admin by right-clicking the batch file and selecting the Run as administrator option.
Source: Windows Central
Once you complete the steps, the batch will run each command in sequence displaying the results in the terminal.
Run batch file on schedule
To schedule a batch file on Windows 10, you can use the Task Scheduler with these steps:
- Open Start.
- Search for Task Scheduler and click the top result to open the app.
- Right-click the «Task Scheduler Library» branch and select the New Folder option.
Type a name for the folder — for example, MyScripts.
Quick note: It’s not a requirement to create a folder, but it’s recommended to keep tasks organized.
Select the Create Basic Task option.
Source: Windows Central
In the «Name» field, type a descriptive name for the task — for example, SystemInfoBatch.
Source: Windows Central
Select the Monthly option.
Source: Windows Central
Quick note: On Windows 10, the Task Scheduler allows you to choose from different triggers, including a specific date, during startup, or when a user signs in to the device. In this case, we’re selecting the option to run a task every month, but you may need to configure additional parameters depending on your requirements.
Use the «Monthly» drop-down menu to pick the months of the year you want to run the task.
Source: Windows Central
Use the «Days» or «On» drop-down menu to confirm the days the task will run.
Source: Windows Central
Select the Start a program option to run the batch file.
Source: Windows Central
Select the batch file you created.
Source: Windows Central
Once you complete the steps, the task will save and run the script on a schedule.
These instructions cover the steps to create a basic task with Task Scheduler. If you want to create a more customizable task, use these instructions.
Run batch files on startup
If you want to execute a sequent of commands every time you sign in to your Windows 10 account, instead of using Task Scheduler, you can place the script in the «startup» folder to save the extra steps.
To run a script on startup on Windows 10, use these easy steps:
- Open File Explorer.
- Browse to the folder with the batch file.
- Right-click the batch file and select the Copy option.
- Use the Windows key + R keyboard shortcut to open the Run command.
Type the following command:
Source: Windows Central
Click the Paste option from the «Home» tab in the Startup folder. (Or Click the Paste shortcut button to create a shortcut to the batch file.)
Source: Windows Central
After you complete the steps, every time you sign in to Windows 10, the batch file will execute and run the included commands.
We’re focusing this guide on Windows 10, but the ability to run batch files has been around for a long time, which means that you can refer to these instructions if you are still on an older version, including Windows 8.1 or Windows 7.
More Windows 10 resources
For more helpful articles, coverage, and answers to common questions about Windows 10, visit the following resources:
Add the best VR headset to your Microsoft Flight Simulator experience
Microsoft Flight Simulator is an impressive game on a standard 2D monitor, but have you experienced it within VR? Grab one of these headsets and take off.
The Dell XPS 15 is our choice for best 15-inch laptop
For a lot of people, a 15-inch laptop is a perfect size that offers enough screen for multitasking, and in a lot of cases, some extra performance from powerful hardware. We’ve rounded up the best of the best at this size.
Halo: MCC’s live service elements make it better, not worse
Halo: The Master Chief Collection is more popular than ever, but some fans don’t agree with the live service approach 343 Industries has taken with it. Here’s why those elements are, at the end of the day, great for the game and for Halo overall.
These are the best PC sticks when you’re on the move
Instant computer — just add a screen. That’s the general idea behind the ultra-portable PC, but it can be hard to know which one you want. Relax, we have you covered!