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.

Steps to create a batch file in Windows:

  1. Open Notepad (or another plain-text editor).
  2. Paste a starter script into the editor.
    @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.

  3. Save the file with a .bat extension via FileSave as.

    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.

  4. Run the batch file from File Explorer by double-clicking it.

    Running an untrusted .bat file can delete data or install unwanted software, so review the contents before execution.

  5. Run the batch file from Command Prompt for troubleshooting.
    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.

  6. Check the script exit code using ERRORLEVEL.
    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.

  7. Extend the batch file with basic logic constructs.
    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.

  8. Schedule the batch file in Task Scheduler for automatic runs.

    Use Action = Start a program and set Start in to the script directory when the batch file relies on relative paths.