Unit 6: Advanced PowerShell and Automation - Subjective Questions
CSC104 — It Fundamentals • Practice Questions with Detailed Answers
20 questions
Define a PowerShell module. Explain how modules are discovered, imported, and used in an automation script.
A PowerShell module is a reusable package containing PowerShell commands, such as functions, cmdlets, variables, aliases, and providers.
- Modules are stored in directories listed in the
$env:PSModulePathenvironment variable. Get-Module -ListAvailabledisplays the modules available on a computer.Import-Module ModuleNameexplicitly imports a module into the current session.- Modern PowerShell can automatically import a module when one of its exported commands is first used.
Get-Command -Module ModuleNamelists commands exported by a module.- A script module normally uses the
.psm1extension, while a module manifest uses.psd1. Export-ModuleMembercontrols which functions, aliases, or variables are exposed.
Modules improve automation by supporting code reuse, maintainability, command organization, and controlled distribution.
Explain how PowerShell can import, process, and export CSV data. Give an example involving a list of users.
PowerShell represents each CSV row as an object whose properties are derived from the column headings.
Import-Csvreads CSV data and creates PowerShell objects.- The pipeline can filter, sort, or transform those objects.
Export-Csvwrites objects back to a CSV file.-NoTypeInformationprevents type metadata from being written in Windows PowerShell.
Example:
$users = Import-Csv -Path "users.csv"
$enabledUsers = $users | Where-Object { $_.Enabled -eq "True" }
$enabledUsers | Select-Object Name, Department |
Export-Csv -Path "enabled-users.csv" -NoTypeInformation
This script imports user records, selects enabled users, retains the required properties, and exports the result. Validation should be added to check that the file exists and that required columns such as Name and Department are present.
Compare the handling of CSV, JSON, and XML files in PowerShell. State an appropriate use case for each format.
CSV stores flat, tabular data.
- Commands:
Import-CsvandExport-Csv - Suitable for reports, spreadsheets, and simple user lists
- It does not naturally represent deeply nested data
JSON stores structured data using objects and arrays.
- Commands:
ConvertFrom-JsonandConvertTo-Json - Suitable for REST APIs, configuration files, and cross-platform data exchange
- The
-Depthparameter may be needed when exporting nested objects
XML stores hierarchical data with elements and attributes.
- It can be loaded using
[xml](Get-Content -Raw -Path "file.xml") - Suitable for complex configuration, legacy systems, and data requiring XPath queries
- It is more verbose than CSV or JSON
The correct format depends on the structure and consumer of the data: use CSV for simple tables, JSON for modern structured interchange, and XML for rich hierarchical or legacy data.
Describe how to create a reusable menu-driven PowerShell script that accepts and validates user choices.
A menu-driven script displays available actions, reads the operator's choice, validates it, and invokes the corresponding command.
A typical design uses:
Write-HostorWrite-Outputto display optionsRead-Hostto collect a choiceswitchto select an action- A
doorwhileloop to redisplay the menu - A specific exit option
- A
defaultbranch for invalid input
Example structure:
do {
Write-Host "1. View services"
Write-Host "2. View processes"
Write-Host "Q. Quit"
$choice = Read-Host "Select an option"
switch ($choice) {
"1" { Get-Service }
"2" { Get-Process }
"Q" { break }
default { Write-Warning "Invalid selection" }
}
} while ($choice -ne "Q")
For maintainability, each action should be placed in a separate function. Destructive operations should require confirmation and should include error handling.
Explain the different methods of collecting input through PowerShell prompts and discuss how input can be validated securely.
PowerShell can collect input in several ways:
Read-Hostreads interactive text input.Read-Host -AsSecureStringmasks sensitive input such as passwords.Get-Credentialcollects a username and password as aPSCredentialobject.- Function parameters accept structured input and are preferable for reusable automation.
PromptForChoice()can present a standardized set of choices.
Input should be validated before it is used:
[ValidateNotNullOrEmpty()]rejects empty values.[ValidateSet()]limits input to approved choices.[ValidateRange()]restricts numeric values.[ValidatePattern()]checks text against a regular expression.[ValidateScript()]performs custom validation.
Sensitive values should not be written to logs or stored as plain text. For unattended automation, credentials should be obtained from an approved secret store rather than embedded in the script.
Explain how PowerShell manages services and processes. Distinguish between service management and process management.
A service is a managed background component that can start automatically and has a defined service state. A process is a currently running program instance.
Service commands include:
Get-Serviceto inspect servicesStart-ServiceandStop-Serviceto change service stateRestart-Serviceto restart a serviceSet-Serviceto change settings such as startup type
Process commands include:
Get-Processto list running processesStart-Processto launch a programStop-Processto terminate a processWait-Processto wait for completion
A service can be installed but not currently running, whereas a process exists only while it is executing. Administrative privileges may be required, and scripts should confirm the target, handle access errors, and avoid forcefully terminating critical system components.
Describe how PowerShell can read and modify the Windows Registry safely. Include suitable commands and precautions.
PowerShell exposes the Windows Registry through the Registry provider. Registry paths can therefore be handled similarly to file-system paths.
Common operations include:
Get-ChildItem HKLM:\Softwareto enumerate keysGet-ItemPropertyto read valuesNew-Itemto create a keyNew-ItemPropertyorSet-ItemPropertyto create or update a valueRemove-ItemPropertyorRemove-Itemto delete data
Example:
$path = "HKLM:\Software\ExampleCompany"
if (-not (Test-Path $path)) {
New-Item -Path $path -Force
}
Set-ItemProperty -Path $path -Name "Enabled" -Value 1
Before making changes, a script should verify the path, back up important data, use -WhatIf where supported, request elevation when necessary, and avoid changing undocumented system keys. It should also consider the differences between 32-bit and 64-bit registry views.
Explain how PowerShell is used to create and manage scheduled tasks. Describe the main components of a task definition.
A scheduled task runs a program or script automatically in response to a time-based or event-based trigger.
Its main components are:
- Action: The command to run, such as
powershell.exewith a script path - Trigger: When the task runs, such as daily, at startup, or at logon
- Principal: The account, logon mode, and privilege level used
- Settings: Conditions, retry behavior, time limits, and power options
PowerShell commands include:
New-ScheduledTaskActionNew-ScheduledTaskTriggerNew-ScheduledTaskPrincipalRegister-ScheduledTaskGet-ScheduledTaskStart-ScheduledTaskUnregister-ScheduledTask
The script path should be absolute, arguments should be quoted correctly, and the selected account must have access to all required resources. Task history, exit codes, and script logs should be reviewed when troubleshooting.
Describe how the Active Directory PowerShell module can be used to create and manage user accounts.
The ActiveDirectory module provides commands for managing domain objects. It can be loaded with Import-Module ActiveDirectory on a system where the appropriate management tools are installed.
Important user-management commands include:
Get-ADUserto find and inspect usersNew-ADUserto create an accountSet-ADUserto update account attributesEnable-ADAccountandDisable-ADAccountto change account statusSet-ADAccountPasswordto reset a passwordAdd-ADGroupMemberto assign group membershipRemove-ADUserto delete an account
A creation script should validate the username, select the correct organizational unit, set required attributes, supply the initial password as a secure string, and use least-privilege credentials. It should also detect duplicate accounts and record success or failure in an audit log.
Design an automation workflow for bulk Active Directory user provisioning from a CSV file. Explain validation, execution, and reporting.
A reliable bulk-provisioning workflow can be divided into the following stages:
- Import: Read records with
Import-Csv. - Schema validation: Confirm required columns such as
GivenName,Surname,SamAccountName,Department, andOU. - Record validation: Reject empty fields, malformed usernames, unknown departments, and invalid organizational-unit paths.
- Duplicate checking: Use
Get-ADUser -Filterto ensure that the username does not already exist. - Preview: Display planned changes and support
-WhatIfwhen practical. - Creation: Call
New-ADUserwith a secure initial password and enable the account according to policy. - Group assignment: Use approved role mappings with
Add-ADGroupMember. - Error handling: Wrap each record in
try/catchso one failure does not stop the complete batch. - Reporting: Record the username, timestamp, status, and error message, then export a summary with
Export-Csv.
The script should use a delegated service identity or approved credentials, avoid storing passwords in the input file, and remain idempotent so rerunning it does not create duplicate accounts.
Define PowerShell Remoting and explain how commands and scripts are executed on one or more remote computers.
PowerShell Remoting allows PowerShell commands to run on remote systems through a managed communication channel. Windows PowerShell commonly uses WinRM and WS-Management, while modern PowerShell can also use SSH.
Key commands include:
Enable-PSRemotingto configure remoting on a Windows hostTest-WSManto test WS-Management connectivityEnter-PSSessionfor an interactive one-to-one sessionInvoke-Commandfor non-interactive execution on one or more computersNew-PSSessionto create a reusable persistent session
Example:
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock {
Get-Service -Name Spooler
}
Objects returned by remoting are usually deserialized representations, so some original methods are unavailable. Secure deployment requires authentication, firewall configuration, trusted host management where applicable, encrypted transport, and least-privilege endpoints.
Compare PowerShell Remoting with PowerShell Jobs. How can they be combined for parallel administration?
PowerShell Remoting and jobs solve different problems.
- Remoting determines where a command runs: on another computer or in another session.
- Jobs determine how a command runs: asynchronously in the background.
Start-Jobcreates a background process job on the local computer.Invoke-Command -AsJobstarts remote work and immediately returns a job object.Start-ThreadJob, when available, uses threads and generally has lower overhead than process-based jobs.
A parallel remote operation can be started with:
$job = Invoke-Command -ComputerName Server01, Server02 `
-ScriptBlock { Get-Process } -AsJob
The administrator can then use:
Get-Jobto inspect stateWait-Jobto wait for completionReceive-Jobto collect outputStop-Jobto cancel workRemove-Jobto clean up job metadata
When combining jobs and remoting, scripts should limit concurrency, preserve the source-computer name in results, handle unreachable hosts, collect errors, and remove completed jobs.
Explain the lifecycle of a PowerShell background job and describe how its output and errors are retrieved.
A background job allows work to continue independently of the interactive prompt.
The typical lifecycle is:
- Create the job with
Start-Job,Start-ThreadJob, orInvoke-Command -AsJob. - Store the returned job object in a variable.
- Inspect its state with
Get-Job. - Wait when necessary using
Wait-Job. - Retrieve output using
Receive-Job. - Stop a long-running job with
Stop-Jobif required. - Remove job metadata with
Remove-Jobafter processing.
Receive-Job normally removes received output from the job's output buffer. The -Keep parameter preserves it for later retrieval. Errors can be examined in the received streams and through properties such as the job's child-job error information. Scripts should explicitly receive results, check the final job state, record failures, and clean up completed jobs.
What is an advanced PowerShell function? Explain the purpose of CmdletBinding, parameter attributes, and validation attributes.
An advanced function behaves similarly to a compiled cmdlet and supports common PowerShell features such as common parameters, parameter binding, pipeline input, and confirmation behavior.
Its main features include:
[CmdletBinding()]enables cmdlet-like behavior and common parameters such as-Verbose,-Debug, and-ErrorAction.param()declares typed parameters.[Parameter(Mandatory)]requires a value.ValueFromPipelineorValueFromPipelineByPropertyNameallows pipeline binding.[ValidateSet()],[ValidateRange()],[ValidatePattern()], and[ValidateScript()]reject invalid arguments.begin,process, andendblocks control pipeline processing.
A function that changes system state can use [CmdletBinding(SupportsShouldProcess)] and call $PSCmdlet.ShouldProcess() to support -WhatIf and -Confirm. These features make functions safer, easier to discover, and suitable for reuse in modules.
Write and explain an advanced function that restarts a service while supporting validation, pipeline input, -WhatIf, and error handling.
One suitable implementation is:
function Restart-ValidatedService {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias("ServiceName")]
[string[]]$Name
)
process {
foreach ($serviceName in $Name) {
try {
$service = Get-Service -Name $serviceName -ErrorAction Stop
if (service.Name, "Restart service")) {
Restart-Service -InputObject $service -ErrorAction Stop
Write-Verbose "Restarted service service.Name)"
}
}
catch {
Write-Error "Could not restart '$serviceName': $($_.Exception.Message)"
}
}
}
}
[CmdletBinding()] creates an advanced function, while SupportsShouldProcess enables -WhatIf and -Confirm. The parameter accepts direct and pipeline input, rejects null or empty names, and supports an alias. -ErrorAction Stop converts command errors into terminating errors so that catch can handle them. The process block ensures that each incoming pipeline item is processed.
Describe the methods available for creating a graphical user interface with PowerShell. What design and threading issues must be considered?
PowerShell can create Windows desktop interfaces using Windows Forms or Windows Presentation Foundation (WPF).
- Windows Forms uses classes from
System.Windows.Formsand is relatively simple for small tools. - WPF uses XAML and supports richer layouts, styling, and data binding.
- Controls can include labels, text boxes, buttons, list views, progress bars, and dialog boxes.
- Event handlers connect user actions, such as button clicks, to PowerShell script blocks.
Important considerations include:
- Validate all values collected from controls.
- Keep administrative logic in functions rather than directly inside event handlers.
- Do not perform long-running work on the UI thread because the interface will freeze.
- Use jobs, runspaces, or asynchronous patterns for lengthy tasks, then safely update the UI.
- Display useful success and error states without exposing sensitive information.
- Apply least privilege, especially when the GUI performs administrative operations.
GUI scripting is useful for controlled operator tools, but command-line automation is usually easier to test and schedule.
Explain how to design log automation in PowerShell for reliable auditing and troubleshooting.
Log automation records what a script attempted, what succeeded, and what failed. A useful log entry normally contains:
- Timestamp
- Severity such as
INFO,WARNING, orERROR - Script or component name
- Target system or object
- Operation performed
- Outcome and error details
- Correlation or run identifier for batch operations
A reusable Write-Log function can format entries and write them using Add-Content, Out-File, Export-Csv, or structured JSON. Structured formats are preferable when logs will be searched or processed automatically.
The design should also include:
- Log rotation or retention to prevent unlimited file growth
- Restricted permissions because logs may contain operational details
- Consistent time zones, preferably UTC in distributed systems
- Separate handling for normal output and errors
- Avoidance of passwords, access tokens, and other secrets
- Optional Windows Event Log or centralized logging integration
Logging failures should be handled carefully so they do not silently hide the outcome of the primary operation.
Design a PowerShell-based system monitoring script for CPU, memory, disk space, services, and event logs. Explain how alerts should be generated.
A system-monitoring script should gather measurements, compare them with defined thresholds, record results, and notify operators only when action is required.
Possible data sources include:
Get-Counteror CIM classes for processor and memory measurementsGet-CimInstance Win32_LogicalDiskfor free disk spaceGet-Servicefor critical service statesGet-WinEventfor recent warning and error eventsTest-ConnectionorTest-NetConnectionfor connectivity checks
The script should:
- Store thresholds in configuration rather than hard-coding them.
- Collect measurements from local or remote systems.
- Calculate values such as disk free percentage using .
- Compare measurements with warning and critical thresholds.
- Write structured results to a log or monitoring platform.
- Send an alert through an approved channel, such as email, a webhook, or an event log.
- Suppress repeated identical alerts for a defined period.
It should handle unavailable hosts, include timestamps and computer names, and return an exit code suitable for a scheduler or monitoring system.
Describe how PowerShell can automate a software deployment task across multiple computers while supporting verification and rollback.
A deployment script should use a controlled sequence rather than only launching an installer.
A suitable workflow is:
- Read the target computers from an approved inventory.
- Test network connectivity and PowerShell Remoting access.
- Check prerequisites, operating-system compatibility, free space, and the currently installed version.
- Copy or download the package and verify its checksum or digital signature.
- Run the installer silently through
Start-Process -Wait, a package provider, orInvoke-Command. - Capture the installer exit code and remote error streams.
- Verify installation by checking the installed version, service state, registry entry, or application health endpoint.
- Record a per-host result in a structured deployment log.
- Roll back or uninstall when verification fails and a supported rollback method exists.
Deployments should be tested in stages, limit parallelism, support -WhatIf where possible, use maintenance windows, and avoid embedding credentials. Idempotent checks prevent unnecessary reinstallation when the desired version is already present.
Explain the principles that make a PowerShell automation script reliable, secure, and maintainable, using user management or system administration as context.
A production-quality automation script should apply several principles:
- Idempotence: Repeated execution should lead to the same desired state without creating duplicate users, tasks, or configuration entries.
- Validation: Validate parameters, input files, paths, identities, and prerequisites before making changes.
- Least privilege: Run with only the permissions required for the operation.
- Secret protection: Use
PSCredential, a secret-management system, or managed identity instead of plain-text passwords. - Error handling: Use
try,catch,finally, and-ErrorAction Stopwhere failures must be intercepted. - Safe execution: Implement
SupportsShouldProcess,-WhatIf, confirmations, and preview reports for state-changing operations. - Logging: Record targets, timestamps, outcomes, and actionable errors without exposing secrets.
- Modularity: Place reusable functions in modules and separate configuration from code.
- Testing: Test functions, failure paths, and validation rules with tools such as Pester.
- Recovery: Define retry, rollback, and cleanup behavior.
For user management, these principles prevent duplicate accounts, incorrect group membership, unauthorized changes, and incomplete audit records. For system tasks, they reduce service disruption and make scheduled or remote execution easier to diagnose.
Define a PowerShell module. Explain how modules are discovered, imported, and used in an automation script.
A PowerShell module is a reusable package containing PowerShell commands, such as functions, cmdlets, variables, aliases, and providers.
- Modules are stored in directories listed in the
$env:PSModulePathenvironment variable. Get-Module -ListAvailabledisplays the modules available on a computer.Import-Module ModuleNameexplicitly imports a module into the current session.- Modern PowerShell can automatically import a module when one of its exported commands is first used.
Get-Command -Module ModuleNamelists commands exported by a module.- A script module normally uses the
.psm1extension, while a module manifest uses.psd1. Export-ModuleMembercontrols which functions, aliases, or variables are exposed.
Modules improve automation by supporting code reuse, maintainability, command organization, and controlled distribution.
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 →