Unit 5 - Notes
CSC104
Unit 5: PowerShell Basics and Core Concepts
1. Introduction to PowerShell
What is PowerShell?
PowerShell is a cross-platform task automation solution made up of a command-line shell, a scripting language, and a configuration management framework. Unlike traditional shells (like Bash or Command Prompt) which accept and return text, PowerShell is built on the .NET framework and accepts and returns objects.
Key Characteristics
- Object-Oriented: Data is manipulated as objects (structured data with Properties and Methods) rather than raw text strings.
- Verb-Noun Syntax: Commands follow a strict naming convention (e.g.,
Get-Service,Stop-Process) making them intuitive to learn. - Extensible: Users can write their own modules and functions.
2. The Environment: Console vs. ISE
The PowerShell Console
- The standard command-line interface (CLI).
- Used for running one-off commands, navigating the file system, and quick administrative tasks.
- Background is typically blue (legacy) or black (modern Terminal).
The Integrated Scripting Environment (ISE)
- A graphical host application.
- Features:
- Script Pane: For writing, editing, and running
.ps1files. - Console Pane: Shows output and accepts interactive commands.
- Syntax Highlighting: Colors code for readability.
- IntelliSense: Provides tab-completion and pop-ups for cmdlet parameters.
- Script Pane: For writing, editing, and running
- Note: While ISE is still available in Windows, Microsoft now recommends Visual Studio Code (VS Code) with the PowerShell extension for modern script development.
3. Cmdlets and The Pipeline
Cmdlets (Command-lets)
Cmdlets are lightweight commands built into the PowerShell environment. They follow a Verb-Noun syntax.
- Verb: Indicates the action (Get, Set, New, Remove, Start, Stop).
- Noun: Indicates the resource (Service, Process, Item, User).
Examples:
Get-Process # Lists running processes
New-Item # Creates a new file or directory
Clear-Host # Clears the screen (alias: cls)
The Pipeline (|)
The pipeline allows you to pass the output of one cmdlet as the input to another cmdlet. Because PowerShell passes objects, you can manipulate data properties without text parsing.
Syntax: Command-1 | Command-2 | Command-3
Example:
# Get all services, pass them to Where-Object to filter for stopped ones
Get-Service | Where-Object {$_.Status -eq 'Stopped'}
Aliases
Shortcuts for cmdlets to speed up typing or help users transitioning from other shells.
lsordir→Get-ChildItemcp→Copy-Itemps→Get-Process
4. Writing Scripts, Variables, and Comments
Writing and Running Scripts
- PowerShell scripts are text files saved with the
.ps1extension. - To run a script in the current directory, you must specify the path:
.\myscript.ps1.
Comments
Comments are ignored by the interpreter and used for documentation.
- Single-line: Starts with
# - Multi-line block: Starts with
<#and ends with#>
# This is a single line comment
<#
This is a
multi-line comment block
#>
Variables
Variables store data for later use.
- Syntax: Always defined with a
$prefix. - Assignment: Uses
=. - Typing: PowerShell is loosely typed (it guesses the type), but you can enforce strong typing.
$name = "Alice" # String
$age = 30 # Integer
[string]$fixedName = 123 # Casts the number 123 to string "123"
User Input
Using Read-Host to pause execution and accept input.
$username = Read-Host -Prompt "Please enter your username"
Write-Host "Hello, $username"
5. Operators
PowerShell uses specific character sequences for operators, particularly for comparisons.
Arithmetic Operators
+(Add),-(Subtract),*(Multiply),/(Divide),%(Modulus/Remainder)
Comparison Operators (Case-insensitive by default)
-eq: Equal to (Equivalent to==in other languages)-ne: Not equal to-gt: Greater than-lt: Less than-ge: Greater than or equal to-le: Less than or equal to
Example:
$val = 10
$val -gt 5 # Returns True
$val -eq 20 # Returns False
Logical Operators
-and: Both conditions must be true.-or: At least one condition must be true.-not(or!) : Inverses the boolean value.
6. Conditional Statements
If / Else / ElseIf
Executes code blocks based on boolean conditions.
$score = 85
if ($score -ge 90) {
Write-Host "Grade: A"
} elseif ($score -ge 80) {
Write-Host "Grade: B"
} else {
Write-Host "Grade: C or lower"
}
Switch
More efficient than multiple if statements when checking a single variable against many values.
$day = "Monday"
switch ($day) {
"Monday" { Write-Host "Start of the work week" }
"Friday" { Write-Host "Weekend is near" }
Default { Write-Host "Just another day" }
}
7. Loops (Iteration)
For Loop
Best when you know exactly how many times you want to loop.
for ($i = 0; $i -lt 5; $i++) {
Write-Host "Counter is $i"
}
ForEach Loop
Used to iterate through a collection (like an array or list of objects).
$servers = "Server1", "Server2", "Server3"
foreach ($server in $servers) {
Write-Host "Pinging $server..."
}
While Loop
Runs as long as a condition is true. Checked at the start of the loop.
$count = 0
while ($count -lt 3) {
Write-Host $count
$count++
}
Do-While / Do-Until
- Do-While: Runs while the condition is true. Checked at the end (guaranteed to run at least once).
- Do-Until: Runs until the condition becomes true.
8. Data Structures: Arrays and Hashtables
Arrays
An ordered list of values.
- Creation:
@()or just comma-separated values. - Indexing: Zero-based (first item is
[0]).
$colors = "Red", "Green", "Blue"
Write-Host $colors[0] # Outputs: Red
$colors += "Yellow" # Adds an item
Hashtables
A collection of Key-Value pairs (dictionary).
- Creation:
@{}. - Access: Using the key name.
$user = @{
Name = "John Doe"
ID = 101
Role = "Admin"
}
Write-Host $user.Name # Outputs: John Doe
Write-Host $user["Role"] # Outputs: Admin
9. Functions and Scoping
Functions
Named blocks of code that perform specific tasks. Increases code reusability.
function Get-Square {
param(
[int]$Number
)
$result = $Number * $Number
return $result
}
Get-Square -Number 5 # Returns 25
Scoping
Scope determines the visibility of variables.
- Global: Accessible everywhere in the current session.
- Script: Accessible only within the script file.
- Local (Function): Accessible only inside the function where defined.
If you define x remains unchanged unless you specify $Global:x = 10.
10. Basic Error Handling
Try / Catch / Finally
Used to handle terminating errors gracefully without crashing the script.
- Try: The code you want to attempt.
- Catch: What to do if an error occurs.
- Finally: Code that runs regardless of success or failure (cleanup).
Try {
# Attempt to divide by zero
$result = 10 / 0
}
Catch {
Write-Host "An error occurred: $($_.Exception.Message)"
}
Finally {
Write-Host "Operation complete."
}
ErrorActionPreference
A built-in variable that controls how PowerShell responds to non-terminating errors.
Continue(Default): Shows error, continues script.Stop: Halts execution immediately (allowsTry/Catchto work on standard errors).SilentlyContinue: Suppresses error messages.
11. Working with Help, Profiles, and Security
The Help System
Get-Help: The primary documentation tool.Get-Help <cmdlet>: Basic view.Get-Help <cmdlet> -Examples: Shows how to use it.Get-Help <cmdlet> -Full: Shows detailed syntax and parameter descriptions.Get-Help <cmdlet> -Online: Opens the documentation in a web browser.
Update-Help: Downloads the latest help files from Microsoft.Get-Member: Used to inspect the properties and methods of an object in the pipeline.- Example:
Get-Process | Get-Member
- Example:
PowerShell Profiles
A profile is a script that runs automatically when you open PowerShell. It is used to customize the environment (aliases, colors, prompts).
- Location variable:
$PROFILE - You must create the file if it doesn't exist to use it.
Execution Policy
A safety feature that controls the conditions under which configuration files and scripts are loaded. It is not a security boundary (it prevents accidental execution, not malicious attacks).
- Restricted: Default. No scripts can run.
- RemoteSigned: Scripts created locally run; downloaded scripts must be signed by a trusted publisher.
- Unrestricted: All scripts run (warns on downloaded files).
- Bypass: Nothing is blocked (used for automation).
Command to change:
Set-ExecutionPolicy RemoteSigned