squirrelworks

Batch scripting

Fundamentals and Functional Differences

1. Evolution of the Command Line

A batch file is a plain-text script used in DOS and Windows to execute a series of commands via the command-line interpreter (cmd.exe). While .bat and .cmd files are functionally similar, they differ significantly in error handling: .cmd updates the ERRORLEVEL variable after every command, whereas .bat only updates when a specific error occurs.

The ERRORLEVEL Reset Behavior

The most significant practical difference is how a successful command affects the system state. In a .cmd file, every successful command resets the error status to zero. In a .bat file, a success does nothing to the previous error state.

@echo off
:: Force an error by trying to 'dir' a non-existent folder
dir \non_existent_folder >nul 2>&1
echo After error: %ERRORLEVEL%

:: Run a successful command
dir >nul
echo After success: %ERRORLEVEL%
Acorn
Behavioral Comparison
  • In a .bat file: The output shows a non-zero error for both checks. The success didn't clear the previous failure.
  • In a .cmd file: The output shows a non-zero error, then 0. The successful dir reset the status.
The Impact on Script Logic

Understanding the ERRORLEVEL reset is not just a technical curiosity; it is a fundamental requirement for error handling. In a .bat script, the error state is "sticky"—once an error occurs, it persists even if subsequent commands are successful.

In a professional environment, .cmd is preferred because it provides deterministic feedback. If you are deploying software or modifying the registry, you need to know if the last action succeeded. A .cmd file ensures the error variable accurately reflects the most recent command, allowing for precise "if-then" logic in automated workflows.

Acorn
The Transition to PowerShell

Legacy scripting has largely been superseded by PowerShell (.ps1). To ease the transition, PowerShell utilizes aliases that map familiar legacy commands to modern cmdlets:

  • dirGet-ChildItem
  • cdSet-Location
  • copyCopy-Item
  • moveMove-Item
  • mkdirNew-Item
  • cls(Internal Native)
2. Legacy Utility in Modern Environments

Despite being "old," Batch remains a lightweight tool for quick automation and diagnostics where PowerShell overhead isn't required. Let’s explore some still-potentially-useful commands and one-liners.

Project Milestone: System Administration One-Liners

1. Hardware and System Audits (WMIC)

The WMIC utility remains a powerful tool for quick system audits, despite its pending removal in future Windows 11 versions.

Check Disk SMART Status:
wmic diskdrive get Availability,Index,Caption,Status
List Installed Hotfixes:
wmic qfe list brief
2. Network and Connectivity Management

Batch scripts are frequently used to automate persistent network mapping and routing table modifications.

Map Persistent Network Drive:
net use T: \\serverNameOrIP\shareName /persistent:yes
Add Static Persistent Route:
route -p add 192.168.1.83 mask 255.255.255.255 172.16.1.1 metric 31 if 11

Project Milestone: Advanced String Manipulation

1. Substring Extraction Syntax

Batch allows for complex string manipulation using the ~ operator—useful for parsing file names or dates.

set ALPHABET=abcdefghijklmnopqrstuvwxyz
:: Extract first 5 characters (abcde)
echo %ALPHABET:~0,5%
:: Omit the last 2 characters
echo %ALPHABET:~0,-2%
Acorn
Warning: Syntax Limitations

This ~ syntax is unique to CMD. Attempting to use this in PowerShell will result in a parsing error.

PowerShell syntax error

Project Milestone: Automation & Domain Management

1. File Searching with forfiles
:: Find files > 1GB starting at C:\
forfiles /P C:\ /S /M * /C "cmd /c if @fsize GEQ 1073741824 echo @path"
2. Automated Domain Join Script
echo "Searching For Domain Status"
for /f "tokens=2" %%i in ('systeminfo ^| find "Domain"') do (set "DOMAIN=%%i")

if "%DOMAIN%" == "WORKGROUP" (
    echo "Joining Domain"
    netdom join /d:mydomain.com %COMPUTERNAME% /ud:[USER] /pd:[PASSWORD]
    shutdown.exe /r /t 00
) else (
    echo "Already in Domain"
)

Project Milestone: The Future of WMIC

Acorn
Depreciation Alert: KB5067470

Starting with Windows 11, version 24H2, WMIC is removed by default. Microsoft recommends transitioning legacy WMIC tasks to PowerShell.

Microsoft Support: WMIC Removal Details

Article Sources & References


Accessibility
 --overview

Agile
 --DevOps overview
 --Principles

API
 --REST best practices
 --REST demo
 --REST vs RPC
 --Wikipedia API

Blockchain
 --overview

Cloud
 --AWS overview

CSS/HTML
 --Bootstrap carousel
 --Grid demo
 --markdown demo

Electricity
 --fundamentals

Encoding
 --Overview

Ergonomics
 --Desk configuration
 --Device fleet
 --Input device array
 --keystroke mechanics
 --Phones & RSI

ERP
 --Anthology overview
 --Ellucian Banner
 --Higher Ed ERP Simulation Lab
 --PeopleSoft Campus Solutions
 --PESC standards
 --Slate data model

Git
 --syntax overview
 --troubleshooting libcrypto

Hardware
 --Device fleet
 --Homelab diagram

Java
 --Fundamentals

Javascript
 --Advanced Interaction: jQuery & UI Frameworks
 --input prompt demo
 --misc demo
 --Time and Date functions
 --Vue demo

Linux
 --grep demo
 --HCI and Proxmox
 --Proxmox install
 --xammp ftp server

Mail flow
 --DKIM, SPF, DMARC
 --MAPI

Microsoft
 --AZ-800: Administering Windows Server Hybrid Core Infrastructure
 --BAT scripting
 --Group Policy
 --IIS
 --robocopy
 --Server 2022 setup - Virtualbox

Misc
 --Applications
 --regex
 --Resources
 --Sustainable Computing
 --Terminology
 --The Humility Protocol: Reality Over Reputation
 --The Jordan Framework: Engineering a Competitive Edge
 --Tribute to Computer Scientists

Networks
 --BGP Peering & Security Hardening Lab
 --CCNA Lammle Study Guide
 --Cisco 1921/K9 router
 --routing protocols
 --throughput calculations

PHP/SQL
 --Cookies
 --database interaction
 --demo, OSI Layers quiz
 --Foreign key constraint demo
 --fundamentals
 --MySQL and PHPmyAdmin setup
 --pagination
 --security
 --session variables
 --SQL fundamentals
 --structures
 --Tables display

Python
 --fundamentals

Security
 --Overview- GRC (Governance, Risk, and Compliance)
 --Security Blog
 --SSH fundamentals

Serialization
 --JSON demo
 --YAML demo