Skip to main content

Lab 7.3: Windows Batch Scripts

Learning Objectives​

By the end of this lab, you will be able to:

  • Create Batch scripts (.bat) for automation
  • Use variables and control structures
  • Manage files and folders in batch
  • Create interactive menus

Estimated Duration​

45 minutes

Prerequisites​

  • Windows 10/11 VM
  • Basic CMD knowledge
  • Text editor (Notepad++)

Professional Context​

Batch scripts are used for:

  • Automating repetitive tasks
  • Installation and configuration
  • System maintenance
  • Startup scripts

Part 1: Basics of Batch Scripting​

Step 1.1: First script​

Create a file first_script.bat:

@echo off
echo =================================
echo MY FIRST BATCH SCRIPT
echo =================================
echo.
echo Hello, welcome to Batch scripting!
echo.
pause

Explanations:

  • @echo off: Hides commands (only shows results)
  • echo: Displays text
  • echo.: Displays a blank line
  • pause: Waits for the user to press a key

Step 1.2: Run the script​

cd C:\path\to\script
first_script.bat

Question 1: What happens if you remove @echo off?

Step 1.3: Variables​

@echo off
echo === BATCH VARIABLES ===
echo.

:: Define variables
set NAME=User
set VERSION=1.0

:: Use variables
echo Hello, %NAME%!
echo Script version: %VERSION%
echo.

:: Environment variable
echo Computer name: %COMPUTERNAME%
echo User: %USERNAME%
echo Date: %DATE%
echo Time: %TIME%

pause

Step 1.4: User input​

@echo off
echo === USER INPUT ===
echo.

set /p FIRSTNAME=Enter your first name:
echo.
echo Hello, %FIRSTNAME%!

set /p AGE=Enter your age:
echo You are %AGE% years old.

pause

Part 2: Control Structures​

Step 2.1: IF Condition​

@echo off
echo === IF CONDITIONS ===
echo.

set /p RESPONSE=Do you want to continue? (Y/N):

if /i "%RESPONSE%"=="Y" (
echo You chose to continue.
) else (
echo Goodbye!
)

pause

IF Options:

  • /i: Case insensitive (Y = y)
  • ==: Equality
  • NEQ: Not equal
  • GTR: Greater than
  • LSS: Less than

Step 2.2: File checking​

@echo off
echo === FILE CHECKING ===
echo.

set FILE=C:\Windows\System32\cmd.exe

if exist "%FILE%" (
echo The file %FILE% exists.
) else (
echo The file does not exist.
)

:: Check a folder
if exist "C:\Temp\" (
echo The folder C:\Temp exists.
) else (
echo The folder does not exist.
mkdir C:\Temp
echo Folder created.
)

pause

Step 2.3: FOR Loop​

@echo off
echo === FOR LOOPS ===
echo.

:: Simple loop
echo Counting from 1 to 5:
for /l %%i in (1,1,5) do echo %%i

echo.

:: Iterate over files
echo .txt files in the current folder:
for %%f in (*.txt) do echo - %%f

echo.

:: Iterate over a folder
echo Contents of C:\Windows (first 5 items):
set COUNT=0
for /d %%d in (C:\Windows\*) do (
set /a COUNT+=1
if !COUNT! LEQ 5 echo - %%d
)

pause

Note: In .bat scripts, use %% for loop variables. In direct command line, use %.


Part 3: Practical Scripts​

Step 3.1: Cleanup script​

Create cleanup.bat:

@echo off
setlocal enabledelayedexpansion

echo ============================================
echo SYSTEM CLEANUP SCRIPT
echo ============================================
echo.

:: Admin check
net session >nul 2>&1
if %errorlevel% neq 0 (
echo [ERROR] This script must be run as administrator.
pause
exit /b 1
)

echo [1/4] Cleaning user temporary files...
if exist "%TEMP%\*" (
del /q /f "%TEMP%\*" 2>nul
echo User temp files cleaned.
) else (
echo No files to clean.
)

echo.
echo [2/4] Cleaning system temporary files...
if exist "C:\Windows\Temp\*" (
del /q /f "C:\Windows\Temp\*" 2>nul
echo System temp files cleaned.
)

echo.
echo [3/4] Emptying recycle bin...
rd /s /q %SYSTEMDRIVE%\$Recycle.Bin 2>nul
echo Recycle bin emptied.

echo.
echo [4/4] Cleanup complete!
echo.

pause

Step 3.2: System information script​

Create system_info.bat:

@echo off
setlocal

echo ============================================
echo SYSTEM INFORMATION
echo ============================================
echo.

:: Date and time
echo Date: %DATE%
echo Time: %TIME%
echo.

:: Machine information
echo === MACHINE ===
echo Name: %COMPUTERNAME%
echo User: %USERNAME%
echo Domain: %USERDOMAIN%
echo.

:: Operating system
echo === OPERATING SYSTEM ===
for /f "tokens=2 delims==" %%a in ('wmic os get caption /value') do echo OS: %%a
for /f "tokens=2 delims==" %%a in ('wmic os get version /value') do echo Version: %%a
echo.

:: Memory
echo === MEMORY ===
for /f "tokens=2 delims==" %%a in ('wmic computersystem get totalphysicalmemory /value') do (
set /a RAM=%%a / 1073741824
echo Total RAM: !RAM! GB
)
echo.

:: CPU
echo === PROCESSOR ===
for /f "tokens=2 delims==" %%a in ('wmic cpu get name /value') do echo CPU: %%a
echo.

:: Disks
echo === DISKS ===
wmic logicaldisk get deviceid,size,freespace /format:table
echo.

:: Network
echo === NETWORK ===
ipconfig | findstr /i "IPv4 Mask Gateway"
echo.

echo ============================================
pause

Step 3.3: Interactive menu​

Create menu.bat:

@echo off
setlocal enabledelayedexpansion

:MENU
cls
echo ============================================
echo MAIN MENU
echo ============================================
echo.
echo 1. System information
echo 2. List processes
echo 3. Network configuration
echo 4. List active services
echo 5. Create a full report
echo 6. Exit
echo.
echo ============================================
set /p CHOICE=Your choice (1-6):

if "%CHOICE%"=="1" goto INFO
if "%CHOICE%"=="2" goto PROCESS
if "%CHOICE%"=="3" goto NETWORK
if "%CHOICE%"=="4" goto SERVICES
if "%CHOICE%"=="5" goto REPORT
if "%CHOICE%"=="6" goto END

echo Invalid choice!
pause
goto MENU

:INFO
cls
echo === SYSTEM INFORMATION ===
systeminfo | findstr /i "OS Version Owner"
echo.
pause
goto MENU

:PROCESS
cls
echo === CURRENT PROCESSES ===
tasklist | more
pause
goto MENU

:NETWORK
cls
echo === NETWORK CONFIGURATION ===
ipconfig /all
pause
goto MENU

:SERVICES
cls
echo === ACTIVE SERVICES ===
net start
pause
goto MENU

:REPORT
cls
echo === CREATING REPORT ===
set REPORT=%USERPROFILE%\Desktop\system_report.txt
echo System report - %DATE% %TIME% > "%REPORT%"
echo ============================== >> "%REPORT%"
echo. >> "%REPORT%"
systeminfo >> "%REPORT%"
echo. >> "%REPORT%"
echo === NETWORK === >> "%REPORT%"
ipconfig /all >> "%REPORT%"
echo. >> "%REPORT%"
echo === SERVICES === >> "%REPORT%"
net start >> "%REPORT%"
echo.
echo Report saved: %REPORT%
pause
goto MENU

:END
cls
echo Goodbye!
timeout /t 2
exit /b 0

Part 4: Error Handling​

Step 4.1: Return codes​

@echo off
echo === ERROR HANDLING ===
echo.

:: Execute a command
ping -n 1 google.com >nul 2>&1

:: Check the result
if %errorlevel%==0 (
echo [OK] Internet connection active
) else (
echo [ERROR] No Internet connection
)

echo.

:: Test file existence
dir C:\Windows\System32\cmd.exe >nul 2>&1
if %errorlevel%==0 (
echo [OK] cmd.exe found
) else (
echo [ERROR] cmd.exe not found
)

pause

Step 4.2: Logging​

@echo off
setlocal

set LOGFILE=C:\Temp\script_log.txt

:: Log function
call :LOG "Script started"

:: Operations
call :LOG "Checking network..."
ping -n 1 127.0.0.1 >nul
if %errorlevel%==0 (
call :LOG "Network OK"
) else (
call :LOG "ERROR: Network KO"
)

call :LOG "Script finished"
echo Log saved: %LOGFILE%
type %LOGFILE%
pause
goto :EOF

:LOG
echo [%DATE% %TIME%] %~1 >> %LOGFILE%
echo [%DATE% %TIME%] %~1
goto :EOF

Part 5: Final Exercise​

Step 5.1: Backup script​

Create a script backup.bat that:

  1. Asks for a source folder
  2. Asks for a destination folder
  3. Creates a backup with the date in the name
  4. Displays a report

Solution:

@echo off
setlocal enabledelayedexpansion

echo ============================================
echo BACKUP SCRIPT
echo ============================================
echo.

:: Ask for paths
set /p SOURCE=Source folder:
set /p DEST=Destination folder:

:: Check paths
if not exist "%SOURCE%" (
echo [ERROR] The source folder does not exist!
pause
exit /b 1
)

if not exist "%DEST%" (
echo The destination folder does not exist. Creating...
mkdir "%DEST%"
)

:: Create backup name with date
for /f "tokens=1-3 delims=/" %%a in ("%DATE%") do set DATESTR=%%c%%b%%a
for /f "tokens=1-2 delims=:" %%a in ("%TIME%") do set TIMESTR=%%a%%b
set BACKUP_NAME=backup_%DATESTR%_%TIMESTR%

:: Create backup folder
set BACKUP_PATH=%DEST%\%BACKUP_NAME%
mkdir "%BACKUP_PATH%"

echo.
echo Backing up from %SOURCE% to %BACKUP_PATH%...
echo.

:: Copy files
xcopy "%SOURCE%\*" "%BACKUP_PATH%\" /E /I /Y /Q

if %errorlevel%==0 (
echo.
echo [OK] Backup completed successfully!
echo Destination: %BACKUP_PATH%

:: Count copied files
for /f %%a in ('dir /s /b "%BACKUP_PATH%\*" 2^>nul ^| find /c /v ""') do echo Files copied: %%a
) else (
echo [ERROR] Backup failed!
)

echo.
pause

Deliverables​

  1. Created Scripts:

    • Cleanup script
    • System information script
    • Interactive menu
    • Backup script
  2. Screenshots:

    • Execution of each script
    • Result of the interactive menu
  3. Questions:

    • Answer to question 1
    • Explain the difference between %variable% and !variable!

Evaluation Criteria​

CriteriaPoints
Basic scripts20%
Control structures25%
Practical scripts30%
Backup script25%

Reference Commands​

:: Variables
set VAR=value
set /p VAR=Prompt:
echo %VAR%

:: Conditions
if "%VAR%"=="value" (command)
if exist file (command)
if %errorlevel%==0 (command)

:: Loops
for /l %%i in (1,1,10) do command
for %%f in (*.txt) do command

:: Files
copy source dest
xcopy source dest /E /I
del file
mkdir folder
rd folder /s /q

:: Redirection
command > file (overwrite)
command >> file (append)
command 2>nul (hide errors)

Lab developed as part of the Operating Systems course - MODULE 7