Unit 6: Advanced PowerShell and Automation
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, andNew-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 withtry,catch, andfinally. - Discoverability:
Get-Command,Get-Help, andGet-Memberreveal commands, syntax, and object structure. - Execution policy: Policies such as
RemoteSignedreduce 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
.psm1file contains functions;Export-ModuleMembercontrols which members are public. - Manifest: A
.psd1file records metadata, dependencies, compatible PowerShell versions, and exported commands. - Discovery: Modules located under paths in
$env:PSModulePathcan be loaded withImport-Module. - Management:
Get-Module -ListAvailablefinds installed modules, whileInstall-Moduleobtains modules from registered repositories. - Example structure:
# 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:
ValueFromPipelineaccepts whole objects;ValueFromPipelineByPropertyNamematches parameter and property names. - Processing blocks:
begininitializes once,processhandles each pipeline item, andendperforms final work. - Safe action:
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-Csvmaps column headings to object properties;Export-Csv -NoTypeInformationwrites tabular data. - JSON:
ConvertFrom-Jsonparses configuration or API responses;ConvertTo-Json -Depth 5controls nested serialization depth. - XML: Casting text as
[xml]creates an XML document whose nodes can be accessed through properties or XPath. - Encoding: Specify
-Encoding utf8where files cross application or platform boundaries. - Example:
$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-Pathbefore 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
doloop redisplays choices until an exit value is selected. - Dispatch:
switchmaps each accepted choice to a command or function. - Validation: A
defaultbranch handles unsupported input without terminating the script. - Design: Keep actions explicit, place operational code in functions, and require confirmation for destructive choices.
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-Hostreturns a string, so numeric or date input should be explicitly converted and validated. - Secrets:
Read-Host -AsSecureStringmasks input; credentials should useGet-Credential. - Confirmation:
ShouldContinue()or common parameters such as-Confirmare 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, andSet-Serviceinspect state, control operation, and configure startup behavior. - Processes:
Get-Processreports properties such asCPUandWorkingSet64;Stop-Process -Id 4120targets a specific process. - Registry: Provider paths such as
HKLM:\SoftwareallowGet-ItemPropertyandSet-ItemPropertyto manage values. - Tasks:
Get-ScheduledTaskandStart-ScheduledTaskinspect 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-ScheduledTaskActiondefines the executable and arguments, such aspowershell.exe -File C:\Ops\Backup.ps1. - Trigger:
New-ScheduledTaskTrigger -Daily -At 2amdefines when execution begins. - Principal: The account and run level determine permissions and whether execution requires an interactive session.
- Registration:
Register-ScheduledTaskcombines 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-FileHashcan 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 $ouscopes searches to a known distinguished name. - Creation:
New-ADUsercan set identity properties, account state, initial password, and destination OU. - Membership:
Add-ADGroupMembergrants group-based access; removal should follow authorization and audit requirements. - Modification:
Set-ADUserchanges supported attributes, whileDisable-ADAccountpreserves 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.
- One-to-one sessions:
Enter-PSSession -ComputerName SRV01provides an interactive remote shell. - One-to-many execution:
Invoke-Command -ComputerName SRV01,SRV02 -ScriptBlock { Get-Service }runs the same operation concurrently.
- Persistent sessions:
New-PSSessionretains 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-Joblaunches work in a separate process, providing isolation with serialization overhead. - Remote job:
Invoke-Command -AsJobtracks asynchronous work performed on remote systems. - Lifecycle:
Get-Jobchecks state,Receive-Jobretrieves output, andRemove-Jobcleans completed job records. - States: Typical states include
Running,Completed,Failed, andStopped. - Example:
$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/catchblock 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-WinEventreads Windows event logs efficiently; application text logs can useGet-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:
$freePercent = [math]::Round(($disk.FreeSpace / $disk.Size) * 100, 2)- Symbols:
$disk.FreeSpaceis unused capacity in bytes;$disk.Sizeis total capacity in bytes;$freePercentis 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.
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 →