Sign In
Sign In

How to Create and Use Batch Files

How to Create and Use Batch Files
Hostman Team
Technical writer
Windows
22.04.2024
Reading time: 7 min

Batch files are text files with .BAT or .CMD extensions that store a set of commands and execute them in the operating system terminal. Such files are necessary to automate standard user work in Windows. 

Batch files can be considered a Windows alternative to the Unix shell scripts which you would run on a Linux server.

This article will describe in detail how to create, configure and run bat files in Windows and which commands to use.

Prerequisites

  • A cloud server or a personal computer with the Windows operating system installed.

  • Notepad or another text editor. We recommend using editors with built-in syntax highlighting, for example, Notepad++.

Create a batch file

To create a Windows bat file, open any text editor and fill it with some content. 

As an example, let's create a batch file that will display the message "Hello, user!" in the Command Prompt window:

@echo off
echo Hello, user!
pause

Now, you need to save the file using the .bat extension. To do this, go to FileSave as….

If you are using Notepad++, select Batch file in the Save as type field and enter the file name.

Image1

When using Notepad, select All files as the file type and enter your file name and extension.

04044ffa Ee06 4954 B80f E44718b2bc0e

If you saved the file with the wrong extension, it can be easily fixed by renaming the file and specifying the correct extension. 

To do this, you need to enable showing file extensions in the Explorer's View tab.

Image6

Syntax of a batch file

Below is a list of basic rules that you need to know when using Windows bat scripting:

  • Each command must be entered on a new line.

  • The commands specified in the file are executed strictly in order, from first to last. The exception is those cases when a transition from one part to another is organized inside the file (for example, goto).

  • Indicate directories in quotes to minimize errors.

  • Add |Y| before commands that require confirmation (such as del or format).

  • You can use two types of commands: internal (built-in) and external. The first are the commands of the Command Prompt (cmd.exe) itself (we'll talk about them later). The second type includes all possible executable files (extensions .EXE, .CMD or .BAT).

  • Use @echo off at the beginning of the file to disable displaying the command line after running the batch file.

Run a batch file

To run a bat file in Windows, simply double-click on it.

It is worth considering that some batch files may contain commands that require administrator rights. In that case, right-click on the file and select Run as administrator

However, if running the file implies some kind of system output, you should run it using the Command Prompt.

To launch the Command Prompt, press WIN+R, enter cmd in the input field, and press Enter. A command line window will open, into which you need to drag-and-drop the batch file and press Enter.

The batch file will begin executing commands and display the result.

Let's run the test file that we created in the previous step and look at the result. If everything works correctly, you will see the message from the file: "Hello, user!".

Image5

Automate .BAT files with Task Scheduler 

A useful feature when working with batch files is the ability to run them at certain intervals. To implement this, you will need to use Task Scheduler, a built-in Windows tool.

  1. Press WIN+R, enter taskschd.msc in the input field and press Enter.

  2. Select Create Basic Task... in the Actions menu on the right. 

  3. After this, the Create Basic Task Wizard window will open, where you need to fill out four tabs:

    • Create a Basic Task. Enter the name and description of the task and click Next.

    • Trigger. Specify how often the batch file should be run and at what time.

    • Action. Select Start a program, click Next and specify the path to the batch file.

    • Finish. Check all entered data and click Finish.

Image3

The batch file is now added to the Windows schedule and will be run automatically according to your settings.

Add comments to batch files

When necessary, you can also add comments to .BAT files in Windows.

There are three ways to leave comments while writing a batch file:

  • rem. Enter the comment immediately after it:

rem your_comment_here
  • Double colon. Works similar to the rem command.

:: your_comment_here
  • goto. This one is used not only for commenting, but also for moving to another part of the batch file. After entering the command, indicate a label (in the example below it is start).

goto start
your_comment_here
:start

Each comment must have its own unique tag.

Basic commands for .BAT files

Below are the main commands used when writing a batch file.

Command

Argument

Description

cd

Catalogue

Going to the specified directory (empty argument returns the current directory).

pause

-

Pausing a batch file.

start

File path/command

Executing the specified program or command in a separate window.

md

Catalogue

Creating a directory.

copy

Path to source files and destination directory

Copying one or more files to a specified directory.

del

File or directory name

Deleting one or more files.

call

Path to the file to run

Running a batch file from another batch file.

title

Title

Changing the window title.

move

Source and destination path to file/files

Moving one file or group of files from one directory to another.

color

Background and text color (set by number or letter)

Changing the background and text color 

exit

-

Terminating the batch file.

This is not a complete list. To check all the commands, write help in the Command Prompt.

Image4

Deploy your cloud server in minutes

Variables

You can also use variables when writing a batch file.

To add a variable, use the set command. First, enter set, then the variable name, then its value. If you need to access a variable and read its value, add the % symbol on both sides of the variable name.

For example: 

@echo off
set example=Hello, user!
echo %example%
pause

Please note that there are no spaces before or after the equal sign, otherwise the program will not work. 

When you run the batch file with this content, the system will output "Hello, user!".

Also, when declaring a variable, you can use the /a flag, which allows to assign a number to the variable. For example:

@echo off
set /a example=2*3
echo %example%
pause

Without the flag, the entire string after the equal sign is assigned to the variable. When run, the program will output the number 6.

In addition to regular variables, there are argument variables. These variables are assigned values that are passed when the batch file is exported. They look like this: %1, %2, %3, etc.

Here's an example:

@echo off
@echo First argument variables - : %1
@echo Second argument variables - : %2
@echo Third argument variables - : %3
pause

When running this batch file, we will pass the string "Hello, user!" The result will be shown in the picture below.

Batch file example: removing unnecessary files

While working, we often end up with unnecessary files that need to be cleaned. A correctly written batch file does an excellent job of this.

Suppose you have a lot of .TXT files in a certain directory and its subdirectories that you no longer need. Let's create a simple batch file for this case:

@echo off
del /f /s /q C:\path_to_directory\Example\*.txt

Let's look at how each flag works:

  • /f allows you to delete all files (even the read-only ones).
  • /s allows you to delete files not only from the directory but also its subdirectories.
  • /q removes confirmation of file deletion.

Now, to test this batch file, let's create the Example directory and the ExampleWithTXT subdirectory, and then add three .TXT files to both:

mkdir Example
cd Example
mkdir ExampleWithTXT
notepad Example1.txt
notepad Example2.txt
notepad Example3.txt
cd ExampleWithTXT
copy C:\path_to_directory\Example\*.txt

Now, drag-and-drop the batch file to the Command Propmpt window and look at the result. The output must show that all six files were successfully removed from the Example directory and the ExampleWithTXT subdirectory.

Image7

Conclusion

In this guide, we described in detail how to create and use .BAT files in Windows and provided basic commands for working with them. Following this tutorial, you can create your first Windows bat script to automate working with the Windows OS.

Windows
22.04.2024
Reading time: 7 min

Similar

Python

How to Install Python on Windows 10

Python is a high-level programming language used by millions of programmers and developers. It is intuitive, offers many useful tools and libraries, and is essential for working with and analyzing large datasets. However, Python is not pre-installed on Windows operating systems. This guide will walk you through installing Python on Windows 10. Which Version to Choose There are two main versions of Python: Python 2 and Python 3, and they are patible. Python 3 was released in 2008 to address issues found in Python 2. It offers more straightforward, intuitive syntax, a wide range of useful libraries (especially for data analysis), and a large community supports it. Python 2 is no longer supported, unlike Python 3. Therefore, for new projects, you only need Python 3. However, if you need to work on projects written in Python 2, you might still need this version, so we will also explain how to install it. How to Install Python 2 To install Python 2 on Windows 10: Open your browser and go to the official website python.org. Go to the Downloads section. In the Downloads section, find the section for specific releases and locate the version you need. The last Python 2 release is 2.7.18. Click on Download and check the related files. For your operating system, download the 64-bit installer (it is the last file in the list). Once the file is downloaded, open it. Before starting the installation, the installer will allow you to choose the installation path and additional tools. Select the necessary options and start the installation. How to Install Python 3 on Windows There are several ways to install Python, each with its own features, advantages, and disadvantages: Full Installation: Installs all components of Python, which is ideal for most projects. Microsoft Store Installation: Suitable for development environments and running scripts. NuGet Package Installation: Python comes as a ZIP file with the .nupkg extension, designed for continuous integration systems. It does not include the user interface. Ideal for building packages and running scripts. Embeddable Package: Installs a minimal version of Python, often used as part of a larger application or project. Full Installation Using the Official Installer The steps for installing Python 3 from the official website are similar to those for Python 2. Here’s how to install Python 3 on Windows 10: Open your browser and go to python.org. Go to the Downloads section. Click on Download Python x.x.x (the latest version). Once you click it, the installer will start downloading. After downloading, open the installer. If Python 3 is already installed, the installer will offer to update it to the version you just downloaded. If Python is not installed, it will offer a fresh installation. Make sure to check the following options: Installing for all users. Add Python to PATH (this allows you to use Python from the command line). There are two installation options: Install now: Administrator rights are not required. Python will be installed in your user directory. Standard libraries, test suites, a launcher, and pip will be installed. Customize Installation: May require administrator rights. Python will be installed in the Program Files directory. Additional features can be installed. The Python standard library can be precompiled into bytecode. Choose the option that suits you and start the installation. After it finishes, disable the MAX_PATH length limitation to avoid errors related to file path length. To check if the installation was successful, run the command python --version in the command line. If everything went well, you should see an output like this: Python 3.10.8 Python is now installed and ready to use. Installing Python via Microsoft Store To install Python from the Microsoft Store: Open the Microsoft Store application. In the search bar, type Python 3.x, specifying the version you want (e.g., "Python 3.10"). Click Get. The download and installation will begin automatically. Installing Python Using NuGet To install Python on Windows via NuGet: Go to the official website and navigate to the Downloads section. Select the recommended version and download it. After opening the downloaded file, installation will take just a few seconds. To install Python, open Windows PowerShell and run the following commands: For the 64-bit version: nuget.exe install python -ExcludeVersion -OutputDirectory For the 32-bit version: nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory Embeddable Package The embeddable package provides a minimal Python environment. It is distributed as a ZIP file and is intended to integrate Python into larger applications. The embeddable package is not designed for direct user access. You will have a fully isolated Python environment when extracted from the archive. It will be isolated from the user’s operating system, including environment variables (like PATH), the system registry, and any installed packages. The standard Python library is included in the embeddable package as compiled and optimized files. However, this version does not include a package manager (pip) or documentation. You can download the embeddable package from the python.org website: Go to the Downloads section. Clicking on Download will download the regular version, so click the hyperlink for Python for Windows instead. Click Latest Python 3 Release - Python x.x.x. Scroll down to the Files section and choose one of the embeddable versions (for 64-bit or 32-bit systems). Conclusion This guide has covered various methods for installing Python on Windows 10. For more useful Python resources, you can explore our tutorials. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
18 October 2024 · 5 min to read
Windows

RDP Protocol: What It Is, What It's Used For, and How It Works

Remote desktop connection to a host can be achieved in various ways, such as using third-party applications like UltraVNC. However, the most common tool for using the Remote Desktop Protocol (RDP) is Microsoft's built-in utility called Remote Desktop. In this article, we'll explore the history of RDP, how it works, and how data is protected during transmission. History of RDP The Remote Desktop Protocol (RDP) was created by Microsoft and initially developed as one of the primary methods for remote access to computers or servers. It was also intended to enable weak local machines to connect to more powerful servers for tasks like complex calculations. Today, RDP is primarily a tool for setting up remote workplaces. Key milestones in the development of RDP: 1998: RDP was first used in Windows NT 4.0 Terminal Server Edition. It continues to be supported in all Windows operating systems, up to Windows 11 and Windows Server 2022. RDP remains a default remote access tool in Windows, despite the existence of other technologies like VNC. There are clients for nearly all major operating systems, including Linux, FreeBSD, macOS, iOS, Android, and more. The current version is RDP 10, which includes features like auto-resizing and enhanced graphics compression using the H.264/AVC codec. General Characteristics of RDP Supported color depths: 32-bit and lower (8, 15, 16, and 24-bit). Data protection: 128-bit encryption using the RC4 algorithm. Other features: Audio redirection, printer and port forwarding, clipboard sharing between the local and remote computers. Citrix Systems played a key role in the early development of remote desktop technology. In the early 1990s, they developed the WinFrame system based on Windows NT 3.51. Citrix eventually collaborated with Microsoft, and in 1997, Microsoft acquired certain rights to Citrix's technology. As a result, Citrix retained rights to the ICA protocol, while Microsoft developed RDP based on the ITU T.120 standard. Citrix and Microsoft remain competitors, with Citrix focusing on high-performance systems and Microsoft leading in the mid-range server market with Terminal Services. Both companies continue to expand their product capabilities to reach more users. Advantages of Terminal Services: Easy application setup for clients. Centralized session management. Functionality tied to active Terminal Services licenses. Network Setup Using Terminal Services Microsoft products allow the use of the RDP protocol in two different modes: for connecting to application servers (Terminal Server Mode) or for managing system settings (Remote Administration Mode). Let's look at both options: Remote Administration Mode All versions of Microsoft Windows support this mode. The only difference is the number of remote connections allowed simultaneously. In desktop versions, only one connection is supported: a local login or a remote host connection. In server versions, the options are broader: two network connections and one local client. Terminal Server Mode This mode is only available on Windows Server editions. The advantage of this mode is that there are no limits on the number of connections—you can have as many as needed. However, you must purchase licenses and configure the system properly to use this mode. The server can be set up as either a dedicated node or a terminal server. Without these steps, access cannot be granted. How RDP Works The Remote Desktop Protocol is an application-layer TCP protocol. Initially, the computers establish a connection. After confirming the connection, the system initiates the RDP session at the transport layer. Once this process is successfully completed, the terminal server begins transmitting the desktop image and allows input from the keyboard and mouse. The display can either be a rendered image or graphical primitives. The system supports the simultaneous use of multiple virtual channels within a single physical connection. This is necessary to enable the following functions: Printing to a printer or data exchange via a serial port. Clipboard functionality and other operations with the disk subsystem. Use of audio playback and recording systems. The parameters for the virtual channels are set at the start, during the initial connection with the host. Two security options are available when initiating a connection: integrated Standard RDP Security and optional Enhanced RDP Security. Let's look at their functionality in more detail and the features of each approach. Standard RDP Security This security approach involves authentication, data encryption, and integrity monitoring through modules integrated into RDP. The encryption uses the RC4 algorithm with a key length between 40-168 bits (depending on the Windows version). When establishing a connection, the system generates a pair of keys to encrypt the information exchanged between the client and the server. The authentication process works as follows: The system generates a pair of RSA keys. It then creates a public key certificate (Proprietary Certificate). This certificate is signed with the RSA key embedded in Windows. The client receives the Proprietary Certificate to access the terminal server. After verifying the certificate, the server's public key is sent to the client. Providing the account and password triggers these actions only upon successful verification. All transmitted data undergoes integrity checks using a Message Authentication Code (MAC) algorithm, based on MD5 and SHA1. The system can be switched to use 3DES encryption, which was introduced in Windows 2003 Server to meet FIPS standards. Enhanced RDP Security The second security option involves using external modules like TLS 1.0 and CredSSP. The TLS protocol was introduced in Windows Server starting with the 2003 release and is used when the client machine supports RDP. Before connecting, it's recommended to check the utility version (RDP 6.0 or higher is required). Users can choose between generating their own certificate or using an existing one from the Windows system. CredSSP (Credential Security Support Provider) is a combined solution that integrates TLS, Kerberos, and NTLM technologies. The advantages of this approach include: Login authorization is verified before completing the RDP connection, saving server resources when dealing with a high number of requests. Encryption and account identification are handled via TLS standards. Single sign-on to the host is supported using Kerberos or NTLM. CredSSP can be selected by enabling the "Use Network Level Authentication" option, available in all operating systems starting with Windows Vista/2008 Server. Terminal Services Licensing  A popular method for accessing Terminal Services is through a "thin client." Its main feature is creating and activating a license server, without which the system will not function (although connections through a "thick client" or to a standard desktop are possible, but only in a remote mode). Licenses are issued in two modes. Without activation, the user is granted a temporary license for the duration of the current session or for a limited period. Once activated, the user is issued a "permanent" license on the server. This process involves issuing a digital certificate confirming the connected workstation's legitimacy. Types of Client Licenses: Temporary Terminal Server CAL: A temporary license limited by a specified period. Device Terminal Server CAL: Tied to a specific device. User Terminal Server CAL: Linked to the specific user defined in the settings. External Terminal Server Connector: Designed for external connections. Let's look at these options in more detail. Time-Based License Upon their first connection to the terminal server, a time-based license is issued to the user. Its validity period is 90 days, regardless of the client's activity. If a second connection is successfully established, the server will attempt to assign a permanent license to the client machine. Licenses must be available in the server's storage for this to happen. Device-Based License This option is designed for a client working from a specific physical device. The license is valid for a period ranging from 52 to 89 days. If 7 or fewer days remain before expiration, the server will attempt to replace it with a permanent license upon any connection attempt. If the device is changed, the cycle will restart from the beginning. User-Based License The user-based license is the most flexible option, as it allows users to work from any device, creating convenient conditions for deploying remote workspaces. A notable feature of this mode is that Terminal Services does not have a built-in connection counter. As a result, when additional clients connect, the number of available licenses remains unchanged. This does not comply with Microsoft's licensing rules, but it is a known fact. If you need to issue both device and user licenses simultaneously, the server must be configured for device-based licensing. In a mixed setup, there will also be no counter for tracking different client connections, and limitations can only be enforced by linking them to specific hardware. External User License This is a special type of license for granting rights to external users. It does not limit the number of clients, regardless of the volume specified, because, under the EULA agreement, a dedicated server must be allocated for such users. This restricts external clients' access to corporate sessions. This type of license is not very popular due to its high cost. RDP Connection on macOS Microsoft has released a Remote Desktop utility for macOS, which you can download from the App Store. The connection process is similar to that on Windows: first, you enter the server's IP address or domain, and then, when prompted, enter the username and password of the user who has remote access rights. After launching, you may receive a warning about an untrusted certificate. To resolve this, simply click "Show Certificate" and select the "Always trust..." option. From then on, the system will connect without asking again. Remote Desktop Connection on Ubuntu When connecting from Windows to a remote host running Ubuntu, the Remote Desktop utility is used, just like on Windows. However, you need to prepare the Ubuntu server by installing support for the technology: sudo apt install xrdp After installation, start the service: sudo systemctl status rdp If you're using Linux as the local machine, the Remmina utility will be useful. You will need to switch the protocol from VNC to RDP. Despite the different systems, the user experience will feel seamless. Other Linux clients include Gnome Connection, Vinagre, Xfreerdp, and Rdesktop. To install the Remmina package: sudo apt-add-repository ppa:remmina-ppa-team/remmina-nextsudo apt-get updatesudo apt-get install remmina remmina-plugin-rdp libfreerdp-plugins-standard Conclusion We've completed our overview of the RDP protocol, covering what it is and how it works. One final note is that a license server can be assigned one of two roles: Domain or Workgroup License Server – operates within a domain or workgroup. Entire Enterprise License Server – operates within an organization. The choice affects how the license server is scanned. In the first case, the system searches through Active Directory, while in the second, it uses NetBIOS broadcast requests.  
16 October 2024 · 9 min to read
Python

How to Install Python on Windows

Python is one of the most talked-about programming languages today, widely used by developers and administrators alike. This language is found everywhere. Even for those who are not software engineers, it is important to understand how to install Python on Windows and start using it.  This article will walk users through the entire process of installing Python on Windows. Let’s dive in and explore it together. Introduction to Python Python is a robust, high-level, interpreted programming language that makes the code readability easy and simple. Its syntax allows developers to express their concepts in fewer lines of code unlike other languages, such as Java or C++. Python also supports multiple programming methods, like object-oriented, functional programming or procedural. This makes it an ideal choice for the programmer to do various types of projects with ease.  Downloading Python for Windows To perform Python installation on Windows, first download the installer file from the official website using the following steps: Step 1: Navigate to the Python Download Page Open any browser on the Windows system.  Then, visit the official Python download page. Step 2: Download Python Click on the “Download Python” button to download the latest version of Python for Windows. The users can also scroll down and select the desired Python version to download on their Windows systems.  After completing these steps, an .exe file will be downloaded. This file is the main installer for Python. The whole process is often referred to as a Python language download. Running the Python Installer After downloading the installer, follow these steps to install Python from the file: Step 1: Run the Installer File Locate the downloaded installer file (.exe), usually found in the Downloads folder.  After finding the installer file, simply double-click on it to run it.  Step 2: Complete the Installation In the installer window, check the box that says “Add python.exe to PATH” to make it easier to run Python from the command line.  To make sure the installation has the necessary permissions, also check the box that suggests “Use admin privileges when installing py.exe”.  Once done, click the “Install Now” button to begin the installation.  Step 3 (Optional): Customize the Installation Users can customize the Python setup for Windows by selecting the “Customize installation” option. Doing this allows them to tailor the installation process to their specific needs. Go with all features, including the one with the install py launcher to make it easier to start Python.  Click “Next” after making the desired selections. In the Advanced Options, users can check the boxes to download debugging symbols and binaries. This is useful for developers who need to debug their Python applications.  Apart from that, a different location can also be selected for Python.  Once done, click the “Install” button. Step 4: Wait for Installation Wait for the installation to complete, since it might take a few minutes. Verifying the Installation Once the installation is complete, verify that Python is installed correctly by following these steps: Open Command Prompt from the Start Menu by simply searching for “cmd” in the search box. In the window of the Command Prompt, enter the following command: python --version After executing the command, the user will see the version of the Python that was installed on the system.  If the above steps have been followed carefully, the user will be able to use Python on Windows without any issues. If an error message appears, it means that Python was not installed correctly. This may occur if the user forgets to check the box that says “Add python.exe to PATH”. If this happens, an additional method, “Setting Up Python in Windows PATH” must be followed which is given below.  Setting Up Python in Windows PATH To set up Python in Windows PATH manually, follow the steps provide below: Step 1: Run Environment Variables From the Start Menu, search for “Environment Variables”.  Then click on the “Edit the system environment variables” option: This will open the System Properties Advanced tab: Step 2: Open Environment Variables Window In the System Properties Advanced tab, click on the “Environment Variables” button. Step 3: Locate the Path Variable In the Environment Variables window, navigate to the “Path” variable in the “System variables” section and select it. Step 4: Edit the Path Variable Double-click on the Path option or select the Path option, click on “Edit” to open the Edit environment variables window.  Once done, simply select the “New” button to add a new entry. Step 5: Add Python Installation Directory In the New entry box, enter the path to the Python installation directory. For example “C:\Users\personal_username\AppData\Local\Programs\Python\Python312\”.  Once done, click the “OK” button to save the changes. Use the “where python” command on Command Prompt to know where is Python installed on the system. Testing the Python Installation To ensure the system completes the Python programming setup, let’s run a simple test. Open Command Prompt from the Start Menu. Enter the following command to run Python interactive shell: python At the interactive shell, the user can now type Python commands or execute codes to see the output. Bonus Tips on Python Installation for Windows The following are some additional tips that can be useful during the installation process: For an instant Python download, the users can use Microsoft Store to quickly install the InstantPython tool. This tool allows them to develop and execute simple Python programs. If the command python3 doesn't work on Windows, it is likely due to the way Python is installed and configured on the system. The simple solution is to move to the Python installation directory and rename the python.exe file to python3.exe. This will fix the issue, and the user will be able to run the python3 command. For users who prefer using PowerShell, the process to download python or python3 for Windows powershell is straightforward. Simply open the PowerShell as administrator and use the following command: Invoke-WebRequest -Uri "https://www.python.org/ftp/python/3.12.6/python-3.12.6-amd64.exe" -OutFile "python-3.12.6-amd64.exe" Summary Python installation on Windows is a straightforward process that opens up a world of programming possibilities. By following the steps provided in this guide, users can ensure that Python is installed correctly and ready to use. Whether developing web applications, exploring AI, or analyzing data, Python is a must on Windows to enhance productivity and capabilities. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
01 October 2024 · 6 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support