Unit 6: Advanced PowerShell and Automation

CSC104 — It Fundamentals 9 min read

I. Orientation — Principles of PowerShell Automation

PowerShell is a cross-platform command-line shell, scripting language, and automation framework introduced by Microsoft in 2006. It processes structured .NET objects rather than relying only on text, allowing administrators to combine commands into repeatable workflows for configuring, monitoring, and managing systems.

  • Object pipeline: Commands pass objects through |; properties and methods remain available to downstream commands.
  • Verb-noun convention: Cmdlets use discoverable names such as Get-Process, Stop-Service, and New-Item.
  • Automation principle: Scripts replace repeated manual actions with consistent, testable, and logged operations.
  • Safety conventions: Use least privilege, validate input, test with -WhatIf, and handle failures with try, catch, and finally.
  • Discoverability: Get-Command, Get-Help, and Get-Member reveal commands, syntax, and object structure.
  • Execution policy: Policies such as RemoteSigned reduce accidental script execution but are not security boundaries.
  • Idempotence: A reliable automation script should produce the intended state without harmful effects when run repeatedly.

II. Reusable PowerShell Components — Packaging and Input Control

A. Modules

A module packages related commands, variables, classes, and resources into a reusable administrative component.

  • Script module: A .psm1 file contains functions; Export-ModuleMember controls which members are public.
  • Manifest: A .psd1 file records metadata, dependencies, compatible PowerShell versions, and exported commands.
  • Discovery: Modules located under paths in $env:PSModulePath can be loaded with Import-Module.
  • Management: Get-Module -ListAvailable finds installed modules, while Install-Module obtains modules from registered repositories.
  • Example structure:
POWERSHELL
# HelpDeskTools.psm1
function Get-ComputerUptime {
    (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
}
Export-ModuleMember -Function Get-ComputerUptime
  • Security: Inspect source, repository trust, signatures, and publisher details before installing third-party modules.

B. Advanced functions with validation

Advanced functions behave like compiled cmdlets and provide parameter binding, validation, common parameters, and pipeline support.

  • Declaration: [CmdletBinding()] enables features such as -Verbose, -ErrorAction, and -WhatIf.
  • Validation: Attributes reject invalid input before the function body runs.
    • [ValidateSet('Start','Stop')] permits listed values.
    • [ValidateRange(1,100)] constrains numbers.
    • [ValidateNotNullOrEmpty()] rejects missing or empty values.
  • Pipeline input: ValueFromPipeline accepts whole objects; ValueFromPipelineByPropertyName matches parameter and property names.
  • Processing blocks: begin initializes once, process handles each pipeline item, and end performs final work.
  • Safe action:
POWERSHELL
function Set-AppService {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('Start','Stop')]
        [string]$Action
    )
    if ($PSCmdlet.ShouldProcess('Spooler', $Action)) {
        & "$Action-Service" -Name Spooler
    }
}

III. Data and Interaction — Files and User Input

A. File handling (CSV, JSON, XML)

PowerShell converts common file formats into objects so data can be filtered, modified, and exported predictably.

  • CSV: Import-Csv maps column headings to object properties; Export-Csv -NoTypeInformation writes tabular data.
  • JSON: ConvertFrom-Json parses configuration or API responses; ConvertTo-Json -Depth 5 controls nested serialization depth.
  • XML: Casting text as [xml] creates an XML document whose nodes can be accessed through properties or XPath.
  • Encoding: Specify -Encoding utf8 where files cross application or platform boundaries.
  • Example:
POWERSHELL
$users = Import-Csv -Path './users.csv'
$enabled = $users | Where-Object Status -eq 'Enabled'
$enabled | ConvertTo-Json | Set-Content './enabled.json' -Encoding utf8
  • Reliability: Validate required properties and use Test-Path before processing; CSV is flat, whereas JSON and XML represent nested data.

B. Menus

Menus present a controlled set of actions for interactive administrative scripts.

  • Construction: A do loop redisplays choices until an exit value is selected.
  • Dispatch: switch maps each accepted choice to a command or function.
  • Validation: A default branch handles unsupported input without terminating the script.
  • Design: Keep actions explicit, place operational code in functions, and require confirmation for destructive choices.
POWERSHELL
do {
    Write-Host '1. Status  2. Restart  Q. Quit'
    $choice = Read-Host 'Select'
    switch ($choice) {
        '1' { Get-Service Spooler }
        '2' { Restart-Service Spooler -Confirm }
        'Q' { break }
        default { Write-Warning 'Invalid selection' }
    }
} until ($choice -eq 'Q')

C. Prompts

Prompts collect runtime values when information cannot safely be predetermined.

  • Text input: Read-Host returns a string, so numeric or date input should be explicitly converted and validated.
  • Secrets: Read-Host -AsSecureString masks input; credentials should use Get-Credential.
  • Confirmation: ShouldContinue() or common parameters such as -Confirm are preferable for consequential operations.
  • Automation limit: Unattended scripts should use parameters, configuration files, or secret stores because interactive prompts block scheduled execution.

IV. Operating-System Administration — Local System Control

A. System tasks (services, processes, registry, tasks)

PowerShell exposes core Windows resources through cmdlets and provider paths.

  • Services: Get-Service, Start-Service, and Set-Service inspect state, control operation, and configure startup behavior.
  • Processes: Get-Process reports properties such as CPU and WorkingSet64; Stop-Process -Id 4120 targets a specific process.
  • Registry: Provider paths such as HKLM:\Software allow Get-ItemProperty and Set-ItemProperty to manage values.
  • Tasks: Get-ScheduledTask and Start-ScheduledTask inspect or launch registered Windows tasks.
  • Privileges: Registry, service, and task changes commonly require elevation; scripts should detect access errors rather than assume success.
  • Targeting: Filter by stable names, IDs, or exact paths to avoid changing unintended resources.

B. Scheduled tasks

Scheduled tasks run programs or scripts in response to a time, event, startup, or logon trigger.

  • Action: New-ScheduledTaskAction defines the executable and arguments, such as powershell.exe -File C:\Ops\Backup.ps1.
  • Trigger: New-ScheduledTaskTrigger -Daily -At 2am defines when execution begins.
  • Principal: The account and run level determine permissions and whether execution requires an interactive session.
  • Registration: Register-ScheduledTask combines the action, trigger, principal, and settings.
  • Operational controls: Use absolute paths, configure retry behavior, write logs, and verify both task history and exit codes.

C. Deployment tasks

Deployment automation installs and configures software consistently across target systems.

  • Stages: Detect prerequisites, copy or download artifacts, verify hashes, install silently, configure settings, and validate the result.
  • Package tools: Depending on policy, scripts may invoke MSI packages, winget, approved repositories, or organization-specific systems.
  • Idempotence: Check the installed version before installation and modify only systems outside the desired state.
  • Integrity: Get-FileHash can verify that an artifact matches an approved digest before execution.
  • Failure strategy: Return meaningful exit codes, preserve installer logs, and define rollback or remediation procedures.

V. Enterprise Administration — Directory and Remote Execution

A. Active Directory

The ActiveDirectory module manages directory objects such as users, groups, computers, and organizational units.

  • Discovery: Get-ADUser -Filter * -SearchBase $ou scopes searches to a known distinguished name.
  • Creation: New-ADUser can set identity properties, account state, initial password, and destination OU.
  • Membership: Add-ADGroupMember grants group-based access; removal should follow authorization and audit requirements.
  • Modification: Set-ADUser changes supported attributes, while Disable-ADAccount preserves an account during offboarding.
  • Safety: Use unique identifiers, constrain search bases, confirm affected counts, and avoid broad wildcard modifications.
  • Dependencies: The AD module, network access to a domain controller, suitable credentials, and delegated permissions are required.

B. PowerShell Remoting

PowerShell Remoting executes commands on remote computers, normally through WS-Management or SSH.

  1. One-to-one sessions: Enter-PSSession -ComputerName SRV01 provides an interactive remote shell.
  2. One-to-many execution: Invoke-Command -ComputerName SRV01,SRV02 -ScriptBlock { Get-Service } runs the same operation concurrently.
  • Persistent sessions: New-PSSession retains remote state and reduces repeated connection overhead.
  • Serialization: Returned objects are usually deserialized snapshots, so some live-object methods are unavailable locally.
  • Authentication: Kerberos is preferred in Windows domains; trusted hosts and credential delegation require careful configuration.
  • Security: Restrict endpoints, use Just Enough Administration where appropriate, and never embed plaintext credentials.

VI. Concurrent and Unattended Work — Background Execution

A. Jobs

Jobs run commands asynchronously so the initiating PowerShell session can continue other work.

  • Background job: Start-Job launches work in a separate process, providing isolation with serialization overhead.
  • Remote job: Invoke-Command -AsJob tracks asynchronous work performed on remote systems.
  • Lifecycle: Get-Job checks state, Receive-Job retrieves output, and Remove-Job cleans completed job records.
  • States: Typical states include Running, Completed, Failed, and Stopped.
  • Example:
POWERSHELL
$job = Start-Job { Get-ChildItem C:\Logs -Recurse | Measure-Object }
Wait-Job $job
$result = Receive-Job $job
Remove-Job $job
  • Caution: Variables and modules may need to be passed or imported explicitly because jobs do not automatically share all caller state.

VII. Interfaces and Operational Automation — Applied Scripts

A. GUI scripting

GUI scripting creates event-driven Windows interfaces, commonly through Windows Forms or Windows Presentation Foundation.

  • Components: Forms contain controls such as labels, text boxes, buttons, lists, and progress bars.
  • Events: Handlers such as $button.Add_Click({ ... }) connect user actions to PowerShell functions.
  • Responsiveness: Long operations should use jobs, runspaces, or asynchronous techniques so the interface does not freeze.
  • Validation: Check user input before invoking administrative commands and display actionable errors.
  • Platform scope: Windows Forms and WPF are primarily Windows technologies; scripts still require proper permissions and deployment controls.
  • Appropriate use: GUIs help occasional operators, while parameters and command-line functions remain better for repeatable unattended automation.

B. Automation scripts for user management

User-management scripts standardize account creation, modification, and removal across a user lifecycle.

  • Provisioning: Read approved records from CSV, validate unique usernames, create accounts, assign groups, and record outcomes.
  • Changes: Update departments, managers, group membership, or license-related attributes from authoritative data.
  • Offboarding: Disable accounts, revoke sessions where supported, remove access, and move objects according to retention policy.
  • Security: Generate passwords securely, avoid logging secrets, apply least privilege, and separate request approval from execution.
  • Auditability: Log the requester, target identity, timestamp, actions, and result without exposing confidential attributes.
  • Resilience: Process each user inside an individual try/catch block so one invalid record does not stop the batch.

C. Log automation

Log automation collects, filters, transforms, archives, and alerts on operational records.

  • Sources: Get-WinEvent reads Windows event logs efficiently; application text logs can use Get-Content.
  • Filtering: Provider-side filters such as -FilterHashtable @{LogName='System'; Level=2} reduce transferred data.
  • Parsing: Structured event properties are more dependable than matching rendered message text.
  • Output: Export selected fields to CSV, JSON, a database, or a centralized logging platform.
  • Rotation: Apply retention limits, timestamp archives, compress older files, and protect logs from unauthorized modification.
  • Incremental processing: Store a checkpoint such as the last record ID or timestamp to prevent duplicate handling.

D. System monitoring

System-monitoring scripts measure availability, performance, and capacity, then report abnormal conditions.

  • Measurements: Get-Counter, Get-CimInstance, Test-Connection, and service cmdlets expose CPU, memory, disk, network, and availability data.
  • Thresholds: A condition such as free disk space below 10% should persist long enough to avoid transient false alerts.
  • Calculation:
POWERSHELL
$freePercent = [math]::Round(($disk.FreeSpace / $disk.Size) * 100, 2)
  • Symbols: $disk.FreeSpace is unused capacity in bytes; $disk.Size is total capacity in bytes; $freePercent is available capacity as a percentage.
  • Response: Record timestamped measurements, alert through approved channels, and automate remediation only when its effects are controlled.
  • Trend value: Historical samples reveal gradual capacity loss that a single point-in-time check cannot identify.