Unit 5: PowerShell Basics and Core Concepts
I. PowerShell Orientation
PowerShell is a cross-platform command-line shell, scripting language, and automation framework created by Microsoft (first released in 2006). Unlike text-oriented shells, it passes structured .NET objects between commands.
A. Introduction to PowerShell
PowerShell provides a consistent environment for administering systems, processing data, and automating repetitive tasks.
- Object-based operation: Commands return objects containing properties and methods, rather than only formatted text.
- Verb-noun naming: Commands normally use names such as
Get-Process,Stop-Service, andNew-Item. - Consistent syntax: Parameters are introduced with
-, as inGet-Service -Name Spooler. - Command discovery: Built-in help and commands such as
Get-Commandmake functionality discoverable. - Platform support: Windows PowerShell 5.1 is Windows-specific, while modern PowerShell 7 runs on Windows, Linux, and macOS.
- Automation: Interactive commands can be placed in
.ps1files and reused as scripts.
II. PowerShell Environments
PowerShell commands can be entered interactively through a console or developed in an editor with scripting support.
A. Console and ISE usage
The console is intended for direct command execution, while an editor provides tools for writing and debugging longer scripts.
- Console:
powershell.exestarts Windows PowerShell, whilepwshstarts PowerShell 7. - Command history: The Up and Down arrow keys recall commands;
Get-Historydisplays commands from the current session. - ISE: Windows PowerShell Integrated Scripting Environment provides a script pane, console pane, syntax highlighting, and debugging.
- ISE limitation: ISE supports Windows PowerShell but not PowerShell 7; Visual Studio Code with the PowerShell extension is the modern alternative.
- Execution: Pressing Enter runs a console command; in ISE,
F5runs a script andF8runs selected code.
B. Working with help
PowerShell's help system explains command syntax, parameters, inputs, outputs, and examples.
- Initial setup:
Update-Helpdownloads current help files and may require an elevated session. - Basic help:
Get-Help Get-Processdisplays documentation forGet-Process. - Detailed forms: Use
-Detailed,-Full,-Examples, or-Onlineto request specific information. - Syntax notation: Items inside square brackets are optional; angle brackets identify expected value types.
- Discovery:
Get-Command *service*searches for commands whose names containservice.
Get-Help Get-Service -Examples
Get-Command -Verb Get -Noun ProcessC. Profiles
A profile is a PowerShell script that runs automatically when a particular host or user session starts.
- Profile path:
$PROFILEstores the path of the current user/current host profile. - Creation:
New-Item -ItemType File -Path $PROFILE -Forcecreates the profile and missing directories. - Typical content: Profiles can define aliases, functions, variables, prompt customization, and module imports.
- Host differences: Console, ISE, and Visual Studio Code can use different profile files.
- Caution: Complex startup commands can slow every session; profiles should contain trusted code only.
III. Commands and Data Flow
PowerShell combines standardized commands with object pipelines to form readable administrative workflows.
A. Cmdlets
A cmdlet is a lightweight PowerShell command, normally named with an approved verb and a singular noun.
- Structure: In
Get-ChildItem,Getis the action andChildItemis the target. - Parameters:
Get-ChildItem -Path C:\Logs -Fileuses named parameters; switches such as-Filerequire no separate value. - Aliases: Names such as
dirandlsmay map toGet-ChildItem, but full cmdlet names make scripts clearer. - Inspection:
Get-Command Get-ChildItem -Syntaxdisplays valid parameter combinations. - Common parameters: Many cmdlets support
-Verbose,-ErrorAction, and-WhatIf.
B. Pipelines
The pipeline operator | sends each command's output objects to the next command.
- Object transfer:
Get-Process | Sort-Object CPUpasses process objects, preserving properties such asName,Id, andCPU. - Filtering:
Where-Objectselects objects according to a condition. - Projection:
Select-Objectchooses properties or limits the number of objects. - Formatting:
Format-TableandFormat-Listshould normally appear at the end because they produce formatting data. - Exporting:
Export-Csvserializes object properties into tabular text.
Get-Service |
Where-Object Status -eq 'Running' |
Select-Object Name, DisplayNameC. Operators
Operators perform arithmetic, assignment, comparison, pattern matching, logical evaluation, and collection processing.
- Arithmetic:
+,-,*,/, and%calculate values;7 % 3returns1. - Assignment:
=,+=,-=,++, and--update variables. - Comparison:
-eq,-ne,-gt,-ge,-lt, and-lereturn Boolean values. - Logical:
-and,-or,-not, and!combine or reverse conditions. - Matching:
-likeuses wildcards,-matchuses regular expressions, and-containschecks collections. - Case sensitivity: Comparisons are case-insensitive by default; forms such as
-ceqenforce case sensitivity.
IV. Script Construction and Decisions
Scripts arrange PowerShell statements into repeatable procedures and use conditions to control which statements run.
A. Writing scripts
Writing a script involves defining a task as an ordered sequence of valid PowerShell statements.
- Planning: Identify required input, processing steps, expected output, and possible failures.
- Readability: Use descriptive names such as
$sourcePathrather than unexplained abbreviations. - Parameters: A
param()block accepts reusable input more reliably than hard-coded values. - Testing: Run small sections first and use
-WhatIfwhere supported before making system changes. - Output: Emit useful objects rather than preformatted text when later pipeline processing is expected.
B. User input
Interactive input can be collected with Read-Host, although script parameters are preferable for unattended automation.
- Text input:
$name = Read-Host 'Enter your name'stores a string. - Conversion:
[int](Read-Host 'Enter quantity')attempts to convert input to an integer. - Secure input:
Read-Host -AsSecureStringavoids displaying sensitive characters. - Automation limitation: Prompts block scheduled tasks, so
param()should be used when values can be supplied in advance.
C. Comments
Comments document intent or temporarily prevent statements from executing.
- Single-line form: Text following
#is ignored by PowerShell. - Block form:
<#begins and#>ends a multiline comment. - Comment-based help: Keywords such as
.SYNOPSIS,.PARAMETER, and.EXAMPLEcan document scripts and functions. - Good practice: Explain non-obvious decisions, assumptions, or side effects rather than restating the code.
D. Conditional statements (if, else, switch)
Conditional statements select code according to Boolean expressions or matching values.
if: Runs a block when its condition evaluates to true.elseifandelse: Test alternatives or provide a fallback path.switch: Compares one or more values against several patterns; options include-Wildcardand-Regex.- Boolean conditions: Comparisons such as
$score -ge 50produce$trueor$false.
if ($score -ge 75) {
'Distinction'
} elseif ($score -ge 50) {
'Pass'
} else {
'Fail'
}V. Repetition and Collections
Loops repeat statements, while arrays and hashtables organize multiple values for efficient processing.
A. Loops (for, foreach, while, do)
Loops execute a code block repeatedly according to a counter, collection, or condition.
for: Best for counter-controlled repetition:for ($i = 0; $i -lt 3; $i++).foreach: Processes every item in a collection:foreach ($file in $files).while: Tests before each iteration, so its body may never execute.do: Tests after execution, sodo { ... } while ($condition)runs at least once.- Control statements:
breakexits a loop, whilecontinueskips to its next iteration.
B. Arrays
An array is an ordered collection whose elements are accessed by zero-based indexes.
- Creation:
$colors = @('Red', 'Green', 'Blue')creates a three-element array. - Indexing:
$colors[0]returnsRed;$colors[-1]returns the final element. - Properties:
$colors.Countreturns3. - Ranges:
$colors[0..1]returns the first two elements. - Iteration: Arrays work naturally with
foreachand the pipeline. - Modification:
+=creates a new array, so mutable generic lists are more efficient for many additions.
C. Hashtables
A hashtable stores values as key-value pairs rather than by numeric position.
- Creation:
$user = @{ Name = 'Asha'; Role = 'Admin' }. - Access:
$user['Name']or$user.NamereturnsAsha. - Updating:
$user.Role = 'Operator'changes the value associated withRole. - Enumeration:
$user.GetEnumerator()produces objects containingKeyandValue. - Ordered form:
[ordered]@{ First = 1; Second = 2 }preserves insertion order.
VI. Reusable Code and Runtime Behavior
Functions package behavior for reuse, while scope and error handling govern state visibility and failure control.
A. Functions
A function is a named script block that can accept parameters, process data, and return output.
- Declaration:
function Get-Greeting { ... }creates a command for the current session. - Parameters: Place
param()first inside the function and add types or validation where useful. - Output: Uncaptured values and command results enter the success output stream.
- Advanced functions:
[CmdletBinding()]enables cmdlet features such as common parameters.
function Get-Square {
param([double]$Number)
$Number * $Number
}B. Variables
Variables are named storage locations whose values can be numbers, strings, objects, or collections.
- Assignment:
$count = 5creates or updates a variable. - Dynamic typing:
$valuecan hold different types over time;[int]$count = 5constrains its type. - Interpolation:
"Count: $count"expands the variable, whereas'Count: $count'remains literal. - Object access:
$process.Namereads theNameproperty of the object in$process. - Built-in variables: Examples include
$true,$false,$null,$HOME, and$PSVersionTable.
C. Scoping
Scope determines where variables, aliases, and functions are visible and where assignments take effect.
- Global scope: Exists for the lifetime of the PowerShell session.
- Script scope: Applies throughout a running script file.
- Local scope: Belongs to the current function or script block.
- Child scopes: Functions and scripts can read values from parent scopes, but ordinary assignments are local.
- Explicit notation:
$global:name,$script:name, and$local:nametarget particular scopes. - Best practice: Prefer parameters and returned objects over modifying global state.
D. Basic error handling
Error handling allows scripts to respond predictably when commands or operations fail.
- Terminating errors: These stop the current operation and can be caught with
tryandcatch. - Non-terminating errors: Many cmdlets report an error but continue;
-ErrorAction Stopconverts them for catching. - Cleanup: A
finallyblock runs whether the operation succeeds or fails. - Manual errors:
throw 'Invalid value'creates a terminating error. - Error details: Inside
catch,$_represents the current error record.
try {
Get-Item -Path $path -ErrorAction Stop
} catch {
Write-Error "Cannot access $path: $($_.Exception.Message)"
}E. Script files
PowerShell scripts are plain-text files with the .ps1 extension that contain executable PowerShell statements.
- Execution: Run a script with
.\Report.ps1; a full or relative path is required unless its directory is in$env:PATH. - Parameters: A top-level
param()block allows calls such as.\Report.ps1 -Path C:\Logs. - Execution policy:
Get-ExecutionPolicy -Listdisplays policy by scope; policy controls script-loading conditions but is not a security boundary. - Signing: Authenticode signatures can verify a script's publisher and detect modification.
- Path reliability:
$PSScriptRootidentifies the script's directory, allowing dependable access to accompanying files. - Dot-sourcing:
. .\Tools.ps1runs a script in the current scope, retaining its functions and variables.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →