Unit 5: PowerShell Basics and Core Concepts

CSC104 — It Fundamentals 9 min read

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, and New-Item.
  • Consistent syntax: Parameters are introduced with -, as in Get-Service -Name Spooler.
  • Command discovery: Built-in help and commands such as Get-Command make 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 .ps1 files 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.exe starts Windows PowerShell, while pwsh starts PowerShell 7.
  • Command history: The Up and Down arrow keys recall commands; Get-History displays 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, F5 runs a script and F8 runs selected code.

B. Working with help

PowerShell's help system explains command syntax, parameters, inputs, outputs, and examples.

  • Initial setup: Update-Help downloads current help files and may require an elevated session.
  • Basic help: Get-Help Get-Process displays documentation for Get-Process.
  • Detailed forms: Use -Detailed, -Full, -Examples, or -Online to 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 contain service.
POWERSHELL
Get-Help Get-Service -Examples
Get-Command -Verb Get -Noun Process

C. Profiles

A profile is a PowerShell script that runs automatically when a particular host or user session starts.

  • Profile path: $PROFILE stores the path of the current user/current host profile.
  • Creation: New-Item -ItemType File -Path $PROFILE -Force creates 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, Get is the action and ChildItem is the target.
  • Parameters: Get-ChildItem -Path C:\Logs -File uses named parameters; switches such as -File require no separate value.
  • Aliases: Names such as dir and ls may map to Get-ChildItem, but full cmdlet names make scripts clearer.
  • Inspection: Get-Command Get-ChildItem -Syntax displays 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 CPU passes process objects, preserving properties such as Name, Id, and CPU.
  • Filtering: Where-Object selects objects according to a condition.
  • Projection: Select-Object chooses properties or limits the number of objects.
  • Formatting: Format-Table and Format-List should normally appear at the end because they produce formatting data.
  • Exporting: Export-Csv serializes object properties into tabular text.
POWERSHELL
Get-Service |
    Where-Object Status -eq 'Running' |
    Select-Object Name, DisplayName

C. Operators

Operators perform arithmetic, assignment, comparison, pattern matching, logical evaluation, and collection processing.

  • Arithmetic: +, -, *, /, and % calculate values; 7 % 3 returns 1.
  • Assignment: =, +=, -=, ++, and -- update variables.
  • Comparison: -eq, -ne, -gt, -ge, -lt, and -le return Boolean values.
  • Logical: -and, -or, -not, and ! combine or reverse conditions.
  • Matching: -like uses wildcards, -match uses regular expressions, and -contains checks collections.
  • Case sensitivity: Comparisons are case-insensitive by default; forms such as -ceq enforce 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 $sourcePath rather than unexplained abbreviations.
  • Parameters: A param() block accepts reusable input more reliably than hard-coded values.
  • Testing: Run small sections first and use -WhatIf where 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 -AsSecureString avoids 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 .EXAMPLE can 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.
  • elseif and else: Test alternatives or provide a fallback path.
  • switch: Compares one or more values against several patterns; options include -Wildcard and -Regex.
  • Boolean conditions: Comparisons such as $score -ge 50 produce $true or $false.
POWERSHELL
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, so do { ... } while ($condition) runs at least once.
  • Control statements: break exits a loop, while continue skips 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] returns Red; $colors[-1] returns the final element.
  • Properties: $colors.Count returns 3.
  • Ranges: $colors[0..1] returns the first two elements.
  • Iteration: Arrays work naturally with foreach and 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.Name returns Asha.
  • Updating: $user.Role = 'Operator' changes the value associated with Role.
  • Enumeration: $user.GetEnumerator() produces objects containing Key and Value.
  • 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.
POWERSHELL
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 = 5 creates or updates a variable.
  • Dynamic typing: $value can hold different types over time; [int]$count = 5 constrains its type.
  • Interpolation: "Count: $count" expands the variable, whereas 'Count: $count' remains literal.
  • Object access: $process.Name reads the Name property 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:name target 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 try and catch.
  • Non-terminating errors: Many cmdlets report an error but continue; -ErrorAction Stop converts them for catching.
  • Cleanup: A finally block 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.
POWERSHELL
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 -List displays 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: $PSScriptRoot identifies the script's directory, allowing dependable access to accompanying files.
  • Dot-sourcing: . .\Tools.ps1 runs a script in the current scope, retaining its functions and variables.