Batch files automate repeatable Windows tasks by running a sequence of commands from a single script, which reduces manual clicking and keeps routine operations consistent across systems and users.
A batch file is a plain-text script saved with a .bat (or .cmd) extension and executed by cmd.exe, which processes the file line by line using built-in commands (such as echo, copy, if, and for) and external programs available in the system path.
Batch scripts run with the permissions of the launching context and can make irreversible changes to files and settings, so careful quoting of paths (especially those with spaces) and a quick test from Command Prompt helps avoid surprises caused by missing privileges or an unexpected working directory.
@echo off setlocal cd /d "%~dp0" echo Script started in: %CD% echo Hello, World! pause
cd /d "%~dp0" switches the working directory to the batch file location, and pause keeps the window open while testing.
Set Save as type to All Files (*.*) or the file may be saved as name.bat.txt and will not execute as a batch script.
Keep the script ASCII-only for maximum compatibility, or select an alternate encoding in the Save as dialog when required by the workflow.
Running an untrusted .bat file can delete data or install unwanted software, so review the contents before execution.
C:\> cd /d C:\Scripts C:\Scripts> hello.bat Script started in: C:\Scripts Hello, World! Press any key to continue . . .
Use cd /d when switching drives, and keep scripts in a dedicated folder such as /C:\Scripts for predictable paths.
C:\Scripts> echo %ERRORLEVEL% 0
Set the exit code with exit /b 0 for success or a non-zero value (for example exit /b 2) to signal failures to other scripts and schedulers.
if exist "C:\Scripts\input.txt" (
echo Found input file.
) else (
echo Missing input file.
exit /b 2
)
for %%F in ("C:\Logs\*.log") do (
echo Processing %%~nxF
)
Loop variables in batch files use two percent signs, while interactive cmd.exe uses one.
Use Action = Start a program and set Start in to the script directory when the batch file relies on relative paths.