Windows Command Prompt Scripting
last modified July 14, 2025
Command Prompt scripting allows automation of repetitive tasks in Windows. Batch files (.bat or .cmd) contain sequences of commands executed by cmd.exe. Scripting saves time by combining multiple commands into reusable files. It enables complex operations through variables, loops, and conditionals. This tutorial covers essential scripting concepts with practical examples.
Batch files are plain text files with commands executed line by line. They support basic programming constructs like variables and flow control. Scripts can accept parameters and interact with users through prompts. Error handling and logging make scripts more robust for production use. Understanding batch scripting is valuable for Windows system administration.
Scripting begins with simple command sequences and progresses to complex logic. The @echo off command suppresses command echoing for cleaner output. Comments start with :: or REM to document script functionality. Environment variables store system information and script configuration. Proper structure and organization make scripts maintainable and reusable.
This tutorial demonstrates practical scripting examples from basic to advanced. Each example focuses on a specific scripting concept or technique. By following along, you'll build skills to create your own automation scripts. The examples progress from simple file operations to system administration. Let's begin with fundamental scripting concepts and examples.
Basic Definitions
Batch file: A text file with .bat or .cmd extension containing cmd commands. Variables: Named storage for values, referenced as %varname% in scripts. Parameters: Values passed to scripts, accessed as %1 through %9. Flow control: Commands like if, for, and goto that alter execution. Redirection: Operators like > and >> that control input/output streams.
Environment variables: System-wide or user-specific configuration values. Command substitution: Using command output as input with %(command)%. Error levels: Numeric codes indicating command success or failure. Labels: Markers for goto commands, defined as :labelname. Functions: Reusable code blocks called with call :function.
Example 1: Basic File Backup Script
This script demonstrates a simple file backup operation. It copies files from a source to destination directory with timestamp. The script shows basic variable usage and command execution.
@echo off setlocal :: Set source and destination folders set SOURCE=C:\Work\Documents set DEST=C:\Backups\Documents_%date:~-4,4%%date:~-10,2%%date:~-7,2% :: Create destination folder if it doesn't exist if not exist "%DEST%" mkdir "%DEST%" :: Copy files echo Backing up files from %SOURCE% to %DEST%... xcopy "%SOURCE%\*.*" "%DEST%\" /E /H /C /I /Q /Y echo Backup completed successfully. endlocal
This script creates dated backups of documents. It uses environment variables for paths and xcopy for robust file copying. The date is formatted as YYYYMMDD.
set SOURCE=C:\Work\Documents
Defines the source directory containing files to backup. Change this path to match your source location. Environment variables make paths configurable.
set DEST=C:\Backups\Documents_%date:~-4,4%%date:~-10,2%%date:~-7,2%
Creates destination path with current date appended. The %date% variable is parsed to extract year, month, and day components for the folder name.
if not exist "%DEST%" mkdir "%DEST%"
Checks if destination folder exists and creates it if needed. The if not exist condition prevents errors when folder already exists.
xcopy "%SOURCE%\*.*" "%DEST%\" /E /H /C /I /Q /Y
Copies all files recursively with attributes. The xcopy switches enable subdirectories (/E), hidden files (/H), and continue on errors (/C).
C:\>backup.bat Backing up files from C:\Work\Documents to C:\Backups\Documents_20250215... 10 File(s) copied Backup completed successfully.
Running the script shows progress and completion message. The actual file count depends on your source directory contents.
Example 2: User Input and Conditional Processing
This script demonstrates interactive input and conditional logic. It prompts for user input and responds differently based on the provided value. The example shows basic decision-making in scripts.
@echo off setlocal :: Prompt for user input set /p choice=Do you want to continue (Y/N)? :: Convert input to uppercase for case-insensitive comparison set choice=%choice:~0,1% set choice=%choice:y=Y% set choice=%choice:n=N% :: Process user choice if "%choice%"=="Y" ( echo Proceeding with operation... timeout /t 3 >nul echo Operation completed. ) else if "%choice%"=="N" ( echo Operation cancelled by user. ) else ( echo Invalid input. Please enter Y or N. ) endlocal
This script handles user confirmation before proceeding. It demonstrates input validation and multiple conditional branches. The timeout simulates processing.
set /p choice=Do you want to continue (Y/N)?
Prompts the user for input and stores response in 'choice' variable. The /p switch enables interactive input in batch files.
set choice=%choice:~0,1% set choice=%choice:y=Y% set choice=%choice:n=N%
Normalizes input by taking first character and converting to uppercase. This makes the comparison case-insensitive while accepting 'y' or 'n'.
if "%choice%"=="Y" ( echo Proceeding with operation... timeout /t 3 >nul echo Operation completed. )
Executes this block if user entered 'Y'. The timeout pauses for 3 seconds (>nul suppresses output) to simulate work.
) else if "%choice%"=="N" ( echo Operation cancelled by user. )
Handles negative response case. The else if construct allows multiple conditions in batch scripts.
C:\>interactive.bat Do you want to continue (Y/N)? y Proceeding with operation... Operation completed.
Sample output shows successful execution path. The script responds differently for 'N' or invalid input.
Example 3: Processing Multiple Files
This script demonstrates processing multiple files with a for loop. It searches for text files and performs operations on each. The example shows batch file iteration capabilities.
@echo off setlocal enabledelayedexpansion :: Set working directory set WORKDIR=C:\Reports cd /d "%WORKDIR%" :: Process each text file echo Processing text files in %WORKDIR%... for %%f in (*.txt) do ( echo ---------------------------- echo Processing: %%f echo File size: %%~zf bytes echo Last modified: %%~tf :: Count lines in file set linecount=0 for /f %%i in ('type "%%f" ^| find /c /v ""') do set linecount=%%i echo Lines: !linecount! :: Create backup copy copy "%%f" "%%~nf.bak" >nul echo Created backup: %%~nf.bak ) echo ---------------------------- echo Finished processing files. endlocal
This script analyzes text files and creates backups. It demonstrates file iteration, property access, and nested commands. Delayed expansion handles variables in loops.
setlocal enabledelayedexpansion
Enables delayed variable expansion for dynamic values in loops. Required when modifying and accessing variables within code blocks.
for %%f in (*.txt) do (
Iterates through all .txt files in current directory. The %%f variable holds each filename during iteration.
echo Processing: %%f echo File size: %%~zf bytes echo Last modified: %%~tf
Displays filename and properties. The modifiers ~z (size) and ~t (timestamp) extract file attributes from the loop variable.
for /f %%i in ('type "%%f" ^| find /c /v ""') do set linecount=%%i
Counts lines in current file. The for /f processes command output, and find /c counts lines. The caret (^) escapes the pipe for nested commands.
C:\>process_files.bat Processing text files in C:\Reports... ------------------------ Processing: report1.txt File size: 1024 bytes Last modified: 02/14/2025 10:30 AM Lines: 42 Created backup: report1.bak ------------------------ Finished processing files.
Output shows file processing details. Each text file gets similar treatment with its specific attributes displayed.
Example 4: System Maintenance Script
This script performs common system maintenance tasks. It cleans temporary files, checks disk space, and generates a report. The example shows administrative scripting techniques.
@echo off setlocal set LOGFILE=%TEMP%\maintenance_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log :: Start logging echo System Maintenance Report > "%LOGFILE%" echo Date: %date% %time% >> "%LOGFILE%" echo ==================================== >> "%LOGFILE%" :: Clean temp files echo [1/3] Cleaning temporary files... del /q /f /s "%TEMP%\*.*" 2>nul echo Temp files cleaned. >> "%LOGFILE%" :: Check disk space echo [2/3] Checking disk space... echo Disk Space: >> "%LOGFILE%" wmic logicaldisk get caption,freespace,size /format:list >> "%LOGFILE%" :: List running services echo [3/3] Checking running services... echo Running Services: >> "%LOGFILE%" sc query state= running >> "%LOGFILE%" :: Complete echo Maintenance completed. Log saved to %LOGFILE% endlocal
This script automates routine system checks. It demonstrates logging, error handling, and system commands. The output is saved to a dated log file.
set LOGFILE=%TEMP%\maintenance_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
Creates log file path in temp directory with current date. The %TEMP% variable points to the system temporary folder.
del /q /f /s "%TEMP%\*.*" 2>nul
Deletes all files in temp directory quietly. The /q enables quiet mode, /f forces deletion, and /s includes subdirectories. Errors are hidden (2>nul).
wmic logicaldisk get caption,freespace,size /format:list >> "%LOGFILE%"
Gets disk space information using WMIC. The output is formatted as a list and appended to the log file.
sc query state= running >> "%LOGFILE%"
Lists all running Windows services. The sc command queries service control manager for service status information.
C:\>maintenance.bat [1/3] Cleaning temporary files... [2/3] Checking disk space... [3/3] Checking running services... Maintenance completed. Log saved to C:\Users\user\AppData\Local\Temp\maintenance_20250215.log
Script shows progress and completion message. Detailed results are in the log file at the specified location.
Example 5: Advanced Script With Functions
This example demonstrates an advanced script with functions and error handling. It provides a menu-driven interface for system information. The script shows modular batch programming techniques.
@echo off setlocal enabledelayedexpansion :: Main script loop :menu cls echo System Information Menu echo ---------------------- echo 1. Display OS Information echo 2. Display Hardware Details echo 3. Display Network Configuration echo 4. Display Running Processes echo 5. Exit echo ---------------------- set /p choice=Enter your choice [1-5]: :: Validate input if "!choice!"=="" goto invalid if "!choice!"=="1" goto osinfo if "!choice!"=="2" goto hardware if "!choice!"=="3" goto network if "!choice!"=="4" goto processes if "!choice!"=="5" exit /b goto invalid :: Function definitions :osinfo call :header "Operating System Information" systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type" pause goto menu :hardware call :header "Hardware Information" echo CPU: wmic cpu get name echo. echo Memory: wmic memorychip get capacity echo. echo Disks: wmic diskdrive get model,size pause goto menu :network call :header "Network Configuration" ipconfig | findstr IPv4 echo. arp -a pause goto menu :processes call :header "Running Processes" tasklist pause goto menu :invalid echo Invalid selection. Please try again. pause goto menu :header echo. echo ==================================== echo %~1 echo ==================================== echo. goto :eof
This script provides a menu-driven system information tool. It demonstrates functions, modular