This chapter covers scripting basics for CompTIA A+ Core 2 (220-1102) Objective 4.6, focusing on Batch, PowerShell, and Bash scripting. Understanding these scripting environments is essential for automating routine tasks, managing systems efficiently, and troubleshooting common issues. Scripting questions appear in approximately 5-10% of the exam, typically as scenario-based questions where you must choose the correct script or command to achieve a specific outcome. You will learn the syntax, common constructs, and practical applications of each scripting language, with an emphasis on what the exam expects you to know.
Jump to a section
Imagine you are a chef in a busy kitchen. You have three main tools: a chef's knife (Batch), a food processor (PowerShell), and a sous chef who follows spoken instructions (Bash). The chef's knife (Batch) is simple, direct, and has been in the kitchen for decades. It can chop vegetables quickly, but every cut is manual—you must specify each slice. It works well for repetitive, straightforward tasks on Windows, but it cannot handle complex recipes without a lot of effort. The food processor (PowerShell) is a modern, powerful appliance. It has multiple blades and settings—it can chop, slice, shred, and even knead dough. It works with ingredients (objects) rather than just slices (text), allowing you to combine tasks seamlessly. It can also automate the entire cooking process, from prepping ingredients to plating. The sous chef (Bash) is a skilled assistant who understands high-level commands. You say 'sauté the onions' and they do it, including peeling, chopping, and timing. Bash excels at chaining commands together with pipes, passing the output of one command as input to the next. In the Linux kitchen, Bash is the master tool, handling everything from simple file operations to complex system administration. On the CompTIA A+ exam, you need to know which tool to use for which task: Batch for legacy Windows scripting, PowerShell for modern Windows automation, and Bash for Linux/macOS environments.
Overview of Scripting in IT
Scripting is the process of writing a series of commands in a file (a script) that can be executed by a command interpreter without manual intervention. On the 220-1102 exam, you must be familiar with three primary scripting environments: Batch (Windows command-line scripts), PowerShell (advanced Windows automation), and Bash (Linux/macOS command-line scripts). Each has its own syntax, strengths, and typical use cases. Scripts are used to automate repetitive tasks, deploy software, configure systems, gather information, and perform maintenance. The exam focuses on recognizing correct syntax, understanding control structures, and identifying appropriate scripting languages for given scenarios.
Batch Scripting
Batch scripts are plain text files with a .bat or .cmd extension that contain commands for the Windows Command Prompt (cmd.exe). They are the oldest form of Windows scripting and are still widely used for simple automation.
#### Syntax and Commands
- @echo off – Hides the command itself from output.
- echo – Outputs text to the console.
- set – Defines or displays environment variables. Syntax: set variable=value (no spaces around =).
- if – Conditional execution. Common forms:
- if exist filename (command)
- if %variable%==value (command)
- for – Looping. Syntax: for %%variable in (set) do (command). Note the double percent sign in scripts.
- goto – Jumps to a label. Labels are defined with a colon, e.g., :label.
- call – Calls another batch file.
- exit /b – Exits the script and returns control.
- rem – Comment.
#### Example Batch Script
@echo off
set source=C:\Data
set dest=D:\Backup
if not exist %dest% mkdir %dest%
for %%f in (%source%\*.txt) do (
copy %%f %dest%
echo Copied %%f
)
echo Backup complete.This script copies all .txt files from C:\Data to D:\Backup, creating the destination folder if needed.
#### Common Exam Traps
- Forgetting @echo off leads to messy output.
- Using single % in a script (only valid at command line).
- Spaces around = in set command cause errors.
- Using if %var%==value without quotes can break if variable is empty.
PowerShell Scripting
PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and scripting language built on .NET. PowerShell scripts use .ps1 extension. PowerShell introduces the concept of cmdlets (pronounced command-lets), which are lightweight commands that return objects, not text.
#### Key Concepts
- Cmdlets: Verb-Noun pairs, e.g., Get-ChildItem, Set-ExecutionPolicy.
- Pipelines: Pass objects between cmdlets using |. Example: Get-Process | Where-Object { $_.CPU -gt 100 }.
- Variables: Prefixed with $, e.g., $name = "Alice".
- Execution Policy: Controls script execution. Default is Restricted on desktop editions. Use Set-ExecutionPolicy RemoteSigned to run local scripts.
- Common Cmdlets for A+:
- Get-ChildItem – Lists files and folders (alias dir, ls).
- Set-Location – Changes directory (alias cd).
- Get-Content – Reads file content (alias cat, type).
- Copy-Item – Copies files/folders.
- Remove-Item – Deletes files/folders.
- New-Item – Creates new items.
- Get-Process – Lists running processes.
- Get-Service – Lists services.
- Write-Host – Outputs to console.
- Write-Output – Sends output to pipeline.
#### Example PowerShell Script
$source = "C:\Data"
$dest = "D:\Backup"
if (-not (Test-Path $dest)) {
New-Item -ItemType Directory -Path $dest
}
Get-ChildItem -Path $source -Filter *.txt | Copy-Item -Destination $dest
Write-Host "Backup complete."This script achieves the same as the Batch example but uses objects and cmdlets.
#### Common Exam Traps
- Confusing Write-Host (directly to console, bypasses pipeline) with Write-Output (sends to pipeline).
- Forgetting to change execution policy before running scripts.
- Using -eq for comparison instead of =.
- Assuming PowerShell is case-sensitive (it is not, but best practice to use PascalCase).
Bash Scripting
Bash (Bourne Again SHell) is the default shell on Linux and macOS. Bash scripts have no extension required but often use .sh. They are text files with a shebang line (#!/bin/bash) at the top.
#### Key Concepts
- Shebang: #!/bin/bash tells the system which interpreter to use.
- Variables: name="Alice" (no spaces around =). Access with $name.
- Conditionals:
- if [ condition ]; then ... fi
- [ -f file ] checks if file exists.
- [ $a -eq $b ] numeric comparison.
- [ $a = $b ] string comparison.
- Loops:
- for var in list; do ... done
- while [ condition ]; do ... done
- Command substitution: $(command) or backticks.
- Pipes: | passes stdout from one command to stdin of next.
- Common commands: ls, cp, mv, rm, grep, awk, sed, chmod, chown.
#### Example Bash Script
#!/bin/bash
source="/home/user/Data"
dest="/mnt/backup"
mkdir -p "$dest"
for file in "$source"/*.txt; do
cp "$file" "$dest"
echo "Copied $file"
done
echo "Backup complete."#### Common Exam Traps
- Forgetting the shebang line – script may run with wrong shell.
- Spaces around = in variable assignment.
- Using if [ $var == "value" ] – == is not POSIX; use = for string comparison.
- Not quoting variables – causes word splitting and globbing issues.
Comparison of Scripting Languages
| Feature | Batch | PowerShell | Bash |
|---------|-------|------------|------|
| Platform | Windows | Windows | Linux/macOS |
| Extension | .bat/.cmd | .ps1 | .sh (or none) |
| Object-based? | No (text) | Yes (.NET objects) | No (text) |
| Execution policy | None | Required | None |
| Common use | Simple tasks | System administration | System administration |
| Loop syntax | for %%i in (set) do | foreach ($i in $set) | for i in list; do |
| Variable prefix | %var% | $var | $var |
Scripting Constructs for the Exam
#### Variables and Environment Variables
- Batch: set var=value, access with %var%. Environment variables like %PATH%, %USERNAME%.
- PowerShell: $var = "value". Environment variables via $env:VAR.
- Bash: var="value", access with $var. Environment variables like $HOME, $PATH.
#### Conditional Statements - Batch:
if exist file.txt (
echo Found
) else (
echo Not found
)- PowerShell:
if (Test-Path file.txt) {
Write-Host "Found"
} else {
Write-Host "Not found"
}- Bash:
if [ -f file.txt ]; then
echo "Found"
else
echo "Not found"
fi#### Loops - Batch:
for %%f in (*.txt) do (
echo %%f
)- PowerShell:
foreach ($file in Get-ChildItem *.txt) {
Write-Host $file.Name
}- Bash:
for file in *.txt; do
echo "$file"
done#### Comments
- Batch: rem comment or :: comment (though :: can cause issues in certain contexts).
- PowerShell: # comment.
- Bash: # comment.
#### Input and Output
- Batch: echo text, set /p var=prompt for input.
- PowerShell: Read-Host "prompt" for input, Write-Host/Write-Output for output.
- Bash: read -p "prompt" var for input, echo for output.
Scripting Best Practices
Always comment your code.
Use meaningful variable names.
Test scripts in a safe environment before production.
Handle errors gracefully (e.g., check if files exist before copying).
Use appropriate quoting to avoid issues with spaces and special characters.
Running Scripts
Batch: Double-click or run script.bat from cmd.
PowerShell: Run .\script.ps1 from PowerShell. Must have appropriate execution policy.
Bash: Make executable with chmod +x script.sh, then run ./script.sh.
Common Use Cases on the Exam
Batch: Simple file operations, running legacy applications, setting environment variables.
PowerShell: Managing Windows services, processes, registry, Active Directory, and remote systems via WinRM.
Bash: File management, process control, text processing (grep, awk, sed), system monitoring.
Security Considerations
Batch: No built-in security; scripts can be easily viewed and modified.
PowerShell: Execution policy helps prevent unauthorized scripts. Use Set-ExecutionPolicy Restricted on high-security systems.
Bash: Scripts rely on file permissions; ensure scripts are owned by root and not writable by others.
Troubleshooting Scripts
Batch: Use echo on to see commands as they execute.
PowerShell: Use Set-PSDebug -Trace 1 or -Verbose parameter.
Bash: Use set -x to trace commands, set -e to exit on error.
What the Exam Specifically Tests
Recognize correct syntax for each language.
Given a scenario, choose the appropriate scripting language.
Identify the purpose of common commands (e.g., Get-ChildItem lists files).
Understand how to run scripts and set execution policy.
Know the differences between Batch, PowerShell, and Bash.
Identify the Task and Platform
Determine what task needs automation (e.g., copying files, managing services, querying system info). Identify the operating system: Windows, Linux, or macOS. For Windows, decide between Batch (simple, legacy) and PowerShell (advanced, modern). For Linux/macOS, Bash is the default. The exam will present a scenario requiring you to choose the correct scripting language based on the OS and complexity.
Choose the Scripting Language
Select Batch if the task is simple, the environment is legacy, or PowerShell is not available. Select PowerShell if you need object manipulation, .NET integration, or remote management. Select Bash for Linux/macOS tasks. The exam may ask which language is best for a given situation, so know the strengths: Batch for quick file ops, PowerShell for deep Windows administration, Bash for Linux sysadmin.
Write the Script with Correct Syntax
Create a text file with the appropriate extension (.bat, .ps1, .sh). Use the correct syntax for variables, conditionals, and loops. For Batch, remember `@echo off` and double `%` in loops. For PowerShell, use `$variables`, cmdlets, and object pipelines. For Bash, include the shebang line, use `$` for variables, and proper quoting. Common mistakes: missing shebang, spaces around `=` in assignments, wrong comparison operators.
Set Execution Permissions (if needed)
On Windows with PowerShell, you must set the execution policy to allow script execution. Use `Set-ExecutionPolicy RemoteSigned` for local scripts. On Linux/macOS, use `chmod +x script.sh` to make the script executable. The exam may ask how to enable script execution or why a script fails to run.
Run the Script and Verify
Execute the script from the command line or shell. For Batch, run `script.bat` from cmd. For PowerShell, run `.\script.ps1` from PowerShell console. For Bash, run `./script.sh`. Verify the output or check that the desired action occurred (e.g., files copied, services started). Troubleshoot using trace options like `echo on` (Batch), `Set-PSDebug -Trace 1` (PowerShell), or `set -x` (Bash).
In a medium-sized enterprise IT department, scripting is used daily to automate routine tasks. For example, a Windows administrator might use a PowerShell script to deploy software updates to 200 workstations. The script would use Invoke-Command to run commands remotely via WinRM, checking each machine's OS version and installing the appropriate patch. The script includes error handling to log failures and retry logic. A common issue is WinRM not being enabled on target machines, causing the script to fail. The administrator must ensure that the execution policy is set to RemoteSigned on the management workstation and that the script is signed or run with appropriate privileges.
Another scenario: a Linux system administrator writes a Bash script to monitor disk usage across 50 servers. The script uses ssh to connect to each server, runs df -h, greps for partitions over 80% usage, and sends an email alert. The script is scheduled via cron to run daily. Challenges include SSH key management, handling server unavailability, and parsing df output correctly. The script must be robust against variations in output format across different Unix flavors.
A third scenario involves a help desk technician who needs to reset user passwords and unlock accounts in Active Directory. Instead of using the GUI for each user, they create a PowerShell script that takes a CSV list of usernames and uses Set-ADAccountPassword and Unlock-ADAccount cmdlets. The script includes logging and confirmation prompts. A common pitfall is insufficient privileges—the script must run with domain admin credentials. The technician might use RunAs or store credentials securely.
In all these cases, scripting reduces human error, saves time, and ensures consistency. Misconfigurations can lead to security vulnerabilities (e.g., scripts with hardcoded passwords) or unintended changes (e.g., deleting wrong files due to incorrect paths). Best practices include testing in a lab, using version control, and implementing proper error handling.
The 220-1102 exam covers scripting as part of Operational Procedures (Objective 4.6). Expect 2-4 questions on scripting, often scenario-based. You must know:
Which scripting language is appropriate for a given OS and task.
Correct syntax for common operations (e.g., loops, conditionals, variables).
How to run scripts and set execution policies.
The purpose of specific commands (e.g., Get-ChildItem, ls, dir).
Common wrong answers and why candidates choose them:
1. Choosing Batch for a complex Windows automation task – Candidates think Batch is the default Windows scripting tool, but PowerShell is far more capable for modern administration.
2. Using `echo` in PowerShell when they should use `Write-Host` – echo is an alias for Write-Output in PowerShell, which sends output to the pipeline, not directly to the console. Candidates confuse it with Batch echo.
3. Forgetting the shebang line in Bash – Candidates write Bash scripts without #!/bin/bash, and the script may run with a different shell (e.g., sh) causing syntax errors.
4. Setting execution policy to `Unrestricted` – This is insecure; the exam expects RemoteSigned for local scripts or AllSigned for stricter environments.
Specific numbers/values to remember:
PowerShell execution policy default: Restricted on client Windows.
Common execution policies: Restricted, RemoteSigned, AllSigned, Unrestricted.
Set-ExecutionPolicy RemoteSigned allows local scripts and signed remote scripts.
Batch loop variable syntax: %%i (double percent).
Bash shebang: #!/bin/bash.
Edge cases the exam loves:
Running a PowerShell script without setting execution policy – error message about execution policy.
Using %i instead of %%i in a Batch script – causes unexpected behavior.
Forgetting to quote variables in Bash that contain spaces – word splitting breaks the script.
Using -eq for assignment instead of = in PowerShell – comparison instead of assignment.
How to eliminate wrong answers:
If the scenario involves Windows and requires object manipulation or remote management, PowerShell is almost always correct.
If the scenario involves Linux/macOS, Bash is correct.
If the scenario involves a simple file copy on Windows, Batch might be acceptable but PowerShell is also possible; look for clues like 'modern' or 'Windows 10'.
If the question asks about 'script execution policy', think PowerShell.
If the question shows a script snippet, check for syntax errors: missing shebang, wrong loop variable, etc.
Batch scripts use .bat/.cmd extension and are executed by cmd.exe.
PowerShell scripts use .ps1 extension and require appropriate execution policy.
Bash scripts use .sh extension (or no extension) and require execute permission.
PowerShell execution policy default is Restricted; use Set-ExecutionPolicy RemoteSigned for local scripts.
In Batch scripts, use %% for loop variables; at command prompt, use %.
In Bash, always include #!/bin/bash at the top of the script.
PowerShell cmdlets follow Verb-Noun naming convention (e.g., Get-ChildItem).
Use Write-Host in PowerShell for direct console output; use Write-Output for pipeline output.
Bash uses $ for variable expansion; no spaces around = in assignment.
The exam may test which scripting language is appropriate for a given OS and task.
These come up on the exam all the time. Here's how to tell them apart.
Batch Scripting
Uses text-based commands; output is plain text.
Limited to Windows command-line tools.
No object pipeline; must parse text output.
No built-in support for remote management.
Easier for simple file operations and legacy compatibility.
PowerShell Scripting
Uses .NET objects; output can be structured data.
Access to all Windows management interfaces (WMI, CIM, .NET).
Object pipeline allows chaining cmdlets seamlessly.
Built-in remoting via WinRM (Enter-PSSession, Invoke-Command).
More powerful for system administration and automation.
Mistake
Batch scripts can use single percent signs in loops.
Correct
In a Batch script (.bat or .cmd), loop variables must be referenced with double percent signs (e.g., `%%i`). Single percent signs (e.g., `%i`) are only valid at the command prompt, not inside a script file.
Mistake
PowerShell's `echo` command works exactly like Batch's `echo`.
Correct
In PowerShell, `echo` is an alias for `Write-Output`, which sends objects to the pipeline. It does not directly write to the console. To write directly to the console, use `Write-Host`. The output of `Write-Output` can be piped further, while `Write-Host` output cannot.
Mistake
Bash scripts do not need a shebang line if they are run with bash explicitly.
Correct
While running `bash script.sh` does not require a shebang, it is a best practice to include `#!/bin/bash` to ensure the script uses the correct interpreter if executed directly. Without it, the system may use a different shell (e.g., sh) which can cause syntax errors.
Mistake
PowerShell execution policy is a security boundary that prevents all malicious scripts.
Correct
Execution policy is a safety feature, not a security boundary. It can be easily bypassed (e.g., by pasting commands into the console). It primarily prevents accidental execution of scripts. For stronger security, use code signing and `AllSigned` policy.
Mistake
Batch scripts are the best choice for modern Windows administration.
Correct
Batch is legacy and limited. PowerShell is the recommended scripting language for Windows administration because it can access .NET, manage objects, and perform complex automation. Batch is only suitable for simple, backward-compatible tasks.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
Batch is a legacy scripting language for Windows that uses simple text commands. It is limited to cmd.exe commands and cannot handle objects. PowerShell is a modern scripting language built on .NET that uses cmdlets and objects. It can manage Windows components like services, registry, and Active Directory more effectively. For the exam, know that PowerShell is preferred for most administrative tasks on Windows, while Batch is used for simple or legacy tasks.
Set-ExecutionPolicy RemoteSigned allows you to run local scripts that you created or scripts from trusted publishers that are signed. This is the recommended policy for most environments. If you set it to Unrestricted, all scripts run but may pose a security risk. On the exam, remember that the default policy is Restricted, which blocks all scripts.
Common reasons: the script does not have execute permission (use chmod +x script.sh), the shebang line is missing or incorrect (should be #!/bin/bash), or there are syntax errors such as spaces around = in variable assignments or missing quotes around variables that contain spaces.
In Batch, use `rem` or `::` (though :: can cause issues in some contexts). In PowerShell, use `#`. In Bash, use `#`. For example: `rem This is a comment` (Batch), `# This is a comment` (PowerShell/Bash).
Use the `for` command with double percent signs: `for %%f in (*.txt) do ( echo %%f )`. This loops through all .txt files in the current directory. The variable `%%f` holds the filename. At the command prompt, use single percent: `for %f in (*.txt) do echo %f`.
PowerShell Core (version 6 and later) is cross-platform and can run on Linux and macOS. However, the exam focuses on PowerShell on Windows. For Linux scripting, Bash is the standard. Be aware that some cmdlets may not work on Linux due to Windows-specific dependencies.
The shebang line (`#!/bin/bash`) tells the operating system which interpreter to use to execute the script. It must be the first line. If omitted, the system may use the default shell (often sh), which can lead to syntax errors if the script uses Bash-specific features.
You've just covered Scripting Basics: Batch, PowerShell, Bash — now see how well it sticks with free 220-1102 practice questions. Full explanations included, no account needed.
Done with this chapter?