Unit 5 subjective questions PowerShell Basics and Core Concepts
CSC104 — It Fundamentals 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define PowerShell and explain how it differs from a traditional command-line shell.
Model answer
PowerShell is a cross-platform command-line shell, scripting language, and automation framework developed by Microsoft. It is built on the .NET platform.
Key differences include:
- Object-based processing: PowerShell passes structured .NET objects between commands, whereas traditional shells generally pass plain text.
- Cmdlets: It provides commands such as
Get-ProcessandGet-Servicethat follow a consistentVerb-Nounnaming convention. - Powerful scripting: It supports variables, functions, loops, conditional statements, modules, and error handling.
- System administration: It can manage files, processes, services, the registry, networks, and remote computers.
- Cross-platform support: Modern PowerShell runs on Windows, Linux, and macOS.
Therefore, PowerShell combines interactive command execution with a full scripting environment for administration and automation.
-
Question 2 of 20
Compare the PowerShell Console and PowerShell ISE. Describe a suitable use case for each.
Model answer
The PowerShell Console is an interactive command-line interface in which commands can be entered and executed immediately.
- It is lightweight and starts quickly.
- It is suitable for running individual commands and short command sequences.
- It displays command output directly in the terminal.
- It is commonly used for routine administration and testing commands.
The PowerShell Integrated Scripting Environment (ISE) is a graphical environment for creating and testing Windows PowerShell scripts.
- It includes a script editor, command pane, and output pane.
- It provides syntax highlighting, tab completion, and debugging tools.
- It allows selected portions of a script to be executed.
- It is suitable for developing and troubleshooting longer scripts.
PowerShell ISE is Windows-specific and is no longer actively developed. For modern PowerShell development, Visual Studio Code with the PowerShell extension is generally preferred.
-
Question 3 of 20
Describe the steps required to create, save, and execute a PowerShell script file. Also explain the purpose of the execution policy.
Model answer
A PowerShell script is a text file with the
.ps1extension.Steps to create and execute a script:
- Open a text editor, PowerShell ISE, or Visual Studio Code.
- Enter PowerShell statements, such as
$name = Read-Host "Enter your name". - Save the file with a
.ps1extension, for exampleGreeting.ps1. - Open PowerShell and move to the script directory using
Set-Locationorcd. - Execute the script using
./Greeting.ps1on PowerShell Core or.\Greeting.ps1on Windows.
The execution policy controls the conditions under which PowerShell loads configuration files and runs scripts. Common policies include
Restricted,RemoteSigned,AllSigned, andBypass. The current policies can be inspected withGet-ExecutionPolicy -List.Execution policy is a safety feature that helps prevent accidental script execution, but it is not a complete security boundary. Policy changes should follow the organization's security requirements.
-
Question 4 of 20
Explain how variables are declared and used in PowerShell. Discuss variable naming, data types, and type casting with examples.
Model answer
A PowerShell variable begins with the
$symbol. A value is assigned using the assignment operator=.Examples:
$name = "Asha"stores a string.$age = 20stores an integer.$isActive = $truestores a Boolean value.
PowerShell variable names are generally case-insensitive. Names should be meaningful and may contain letters, numbers, and underscores. Braces can remove ambiguity in complex names, as in
${student-name}.PowerShell normally determines the data type automatically. The type can be examined using
$age.GetType().A type can also be specified explicitly:
[int]$quantity = 5[string]$code = 101[datetime]$today = "2025-01-01"
Type casting converts a value to another compatible type. For example,
[int]"25"converts the string"25"to an integer. An invalid conversion produces an error. -
Question 5 of 20
Explain how PowerShell accepts user input. Write and explain a script that reads two numbers and displays their sum.
Model answer
PowerShell commonly accepts interactive input through the
Read-Hostcmdlet. SinceRead-Hostnormally returns a string, numeric input should be converted to a suitable numeric type.Example script:
[double]$first = Read-Host "Enter the first number" [double]$second = Read-Host "Enter the second number" $sum = $first + $second Write-Output "Sum = $sum"Explanation:
Read-Hostdisplays a prompt and waits for the user to enter a value.[double]converts each input value to a number that can include a decimal part.- The
+operator adds the two numeric values. Write-Outputsends the result to the PowerShell output stream.
Without numeric conversion, two string values could be concatenated instead of added. Production scripts should also validate the input or handle conversion errors.
-
-
Question 6 of 20
Distinguish between single-line comments, block comments, and comment-based help in PowerShell.
Model answer
PowerShell supports comments for documentation and for temporarily preventing code from being executed.
- Single-line comment: Begins with
#and continues to the end of the line. Example:# Calculate the total. - Block comment: Begins with
<#and ends with#>. It can span several lines and is useful for longer explanations. - Comment-based help: Uses specially recognized keywords inside a block comment to document a script or function.
A comment-based help section may contain:
.SYNOPSISfor a brief description..DESCRIPTIONfor detailed information..PARAMETERfor parameter documentation..EXAMPLEfor usage examples..NOTESfor additional information.
After comment-based help is added correctly, users can view it through
Get-Help. Comments should explain the purpose or reasoning of code rather than merely repeat what each statement does. - Single-line comment: Begins with
-
Question 7 of 20
What is a PowerShell cmdlet? Explain its naming convention, parameters, aliases, and command-discovery facilities.
Model answer
A cmdlet is a lightweight PowerShell command designed to perform a specific operation. Cmdlets usually produce and consume structured objects.
PowerShell cmdlets use the
Verb-Nounnaming convention:- The verb identifies the action, such as
Get,Set,New, orRemove. - The noun identifies the resource, such as
Process,Service, orItem.
For example,
Get-Processretrieves process objects. Parameters modify command behavior, as inGet-Process -Name powershell. Switch parameters represent Boolean choices, such as-Force.An alias is an alternative short name for a command. For example,
gciis an alias forGet-ChildItem. Full cmdlet names are preferable in scripts because they are clearer.Useful discovery commands include:
Get-Commandto find commands.Get-Aliasto inspect aliases.Get-Verbto list approved verbs.Get-Helpto read command documentation.
- The verb identifies the action, such as
-
Question 8 of 20
Explain the PowerShell pipeline and demonstrate how objects move through a multi-stage pipeline.
Model answer
The PowerShell pipeline uses the
|operator to send output from one command to the next command. Unlike many traditional shells, PowerShell normally passes objects, including their properties and methods, rather than unstructured text.Example:
Get-Process | Where-Object { $_.CPU -gt 10 } | Sort-Object CPU -Descending | Select-Object -First 5 Name, CPUPipeline stages:
Get-Processcreates process objects.Where-Objectfilters objects whoseCPUproperty is greater than10.$_represents the current pipeline object.Sort-Objectsorts the remaining objects by CPU usage.Select-Objectreturns the first five objects with only theNameandCPUproperties.
Because object properties remain available in the pipeline, commands can filter, sort, group, measure, and export data without manually parsing formatted text.
-
Question 9 of 20
Classify the major operators available in PowerShell and provide examples of their use.
Model answer
PowerShell operators can be classified by their purpose.
- Arithmetic operators:
+,-,*,/, and%. Example:$remainder = 17 % 5. - Assignment operators:
=,+=,-=,*=, and/=. Example:$total += 10. - Comparison operators:
-eq,-ne,-gt,-ge,-lt, and-le. Example:$age -ge 18. - Logical operators:
-and,-or,-not, and!. Example:($age -ge 18) -and $hasID. - String and pattern operators:
-like,-notlike,-match, and-replace. Example:$name -like "A*". - Containment operators:
-contains,-notcontains,-in, and-notin. Example:$role -in @("Admin", "Editor"). - Type operators:
-is,-isnot, and-as. Example:$value -is [int].
PowerShell comparison operators are case-insensitive by default. Prefixing them with
c, as in-ceq, performs a case-sensitive comparison. - Arithmetic operators:
-
Question 10 of 20
Describe the syntax and working of
if,elseif, andelsestatements. Write a PowerShell example that assigns a grade from a numeric score.Model answer
Conditional statements execute different blocks of code according to whether Boolean conditions are true or false. PowerShell evaluates
iffirst, then eachelseifin order, and finallyelseif no earlier condition is true.Example:
[int]$score = Read-Host "Enter the score" if ($score -lt 0 -or $score -gt 100) { $grade = "Invalid score" } elseif ($score -ge 80) { $grade = "A" } elseif ($score -ge 60) { $grade = "B" } elseif ($score -ge 40) { $grade = "C" } else { $grade = "Fail" } Write-Output "Grade: $grade"The conditions are ordered from the highest score boundary to the lowest. Only the first matching block is executed. The initial condition prevents values outside the valid range from being graded.
-
Question 11 of 20
Explain the
switchstatement in PowerShell. How can it be used for exact, wildcard, and regular-expression matching?Model answer
The
switchstatement compares one or more input values against several conditions. It is often clearer than a long chain ofelseifstatements.Exact matching:
switch ($choice) { "start" { "Starting service"; break } "stop" { "Stopping service"; break } default { "Unknown choice" } }PowerShell also supports different matching modes:
switch -Wildcard ($value)permits patterns such as"Error*".switch -Regex ($value)permits regular expressions such as"^ERR\d+$".switch -CaseSensitive ($value)performs case-sensitive matching.switch -File pathevaluates each line of a file.
The automatic variable
$_represents the current input value inside a matching block. Unlikeswitchin some languages, PowerShell may execute multiple matching clauses. Thebreakstatement can stop further matching when only one result is required. -
Question 12 of 20
Compare the
for,foreach,while, anddoloops in PowerShell. State when each loop is appropriate.Model answer
PowerShell provides several loop structures for repeated execution.
forloop: Best when initialization, a continuation condition, and an update expression are known. Example:for ($i = 0; $i -lt 5; $i++) { $i }.foreachstatement: Best for processing every item in a collection. Example:foreach ($name in $names) { $name }.whileloop: Tests its condition before each iteration. It may execute zero times. Example:while ($count -lt 5) { $count++ }.doloop: Executes the body before testing its condition, so it runs at least once. It can use eitherdo { } while (condition)ordo { } until (condition).
breakexits a loop immediately, whereascontinueskips the remainder of the current iteration. A loop must update the state used in its condition; otherwise, it may become an infinite loop. -
Question 13 of 20
Explain arrays in PowerShell. Describe how to create, access, modify, iterate over, and inspect an array.
Model answer
An array is an ordered collection of values. PowerShell arrays can contain values of the same type or mixed types.
Creation:
$colors = @("Red", "Green", "Blue")$numbers = 1..5[int[]]$scores = 70, 80, 90
Access and inspection:
$colors[0]returns the first element.$colors[-1]returns the last element.$colors[0..1]returns a range of elements.$colors.Countgives the number of elements.
An existing element can be changed using
$colors[1] = "Yellow". An item can be appended using$colors += "Black", although repeated use of+=can be inefficient for large collections because arrays have fixed size internally.Arrays can be processed with
foreach ($color in $colors) { $color }or through the pipeline. Methods and operators such as-contains,Where-Object, andSort-Objectcan be used to search, filter, and arrange their elements. -
Question 14 of 20
What is a PowerShell hashtable? Explain how to create, access, update, remove, and enumerate key-value pairs.
Model answer
A hashtable stores data as key-value pairs. It is useful when values need to be retrieved by meaningful keys rather than numeric indexes.
Creation:
$student = @{ Name = "Ravi" Age = 20 Course = "IT" }Operations:
- Access by key:
$student["Name"]or$student.Name. - Add or update a value:
$student["Grade"] = "A". - Update an existing value:
$student.Age = 21. - Check for a key:
$student.ContainsKey("Course"). - Remove a key:
$student.Remove("Course"). - Obtain keys or values:
$student.Keysand$student.Values.
Enumeration:
foreach ($entry in $student.GetEnumerator()) { "entry.Key): entry.Value)" }A normal hashtable does not guarantee display order. An ordered dictionary can be created with
[ordered]@{ Name = "Ravi"; Age = 20 }when insertion order matters. - Access by key:
-
Question 15 of 20
Describe how functions are defined in PowerShell. Write an advanced function with a parameter, validation, pipeline support, and a return value.
Model answer
A PowerShell function is a named reusable block of code. Parameters receive values from callers, and output is returned through the success output stream.
Example advanced function:
function Get-Square { [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)] [ValidateRange(-1000, 1000)] [double]$Number ) process { $Number * $Number } } 2, 4, 6 | Get-SquareExplanation:
function Get-Squaredeclares the function.[CmdletBinding()]gives it advanced-function behavior.paramdefines its parameters.Mandatoryrequires a value when the function is called directly.ValueFromPipelineallows pipeline input.ValidateRangerejects values outside the permitted range.- The
processblock runs once for each pipeline input object. $Number * $Numberwrites the calculated value to the output stream.
PowerShell functions usually should emit objects or values instead of presentation-only text so their output can be reused in pipelines.
-
Question 16 of 20
Explain variable scope in PowerShell. Distinguish among global, script, local, and private scopes.
Model answer
A scope determines where a variable, function, or alias is visible and where it can be modified.
- Global scope: Created when PowerShell starts. An explicitly global variable can be referenced as
$global:name. - Script scope: Exists while a script file runs. A script-level variable can be referenced as
$script:name. - Local scope: Represents the current scope. Functions and script blocks generally create child local scopes. It can be referenced as
$local:name. - Private scope: Prevents an item from being visible to child scopes. A private variable can be declared as
$private:name.
A child scope can normally read values from a parent scope, but assigning to an unqualified variable usually creates or changes a variable in the current scope. Scope modifiers should be used deliberately because excessive global state makes scripts difficult to test and maintain. Passing values through parameters and returning output is usually preferable.
- Global scope: Created when PowerShell starts. An explicitly global variable can be referenced as
-
Question 17 of 20
Explain basic error handling in PowerShell using
try,catch,finally,throw, and-ErrorAction.Model answer
PowerShell distinguishes between terminating and non-terminating errors. A
tryblock handles terminating errors, while many cmdlets produce non-terminating errors by default.Example:
try { $content = Get-Content -Path "data.txt" -ErrorAction Stop if ($content.Count -eq 0) { throw "The file is empty." } $content } catch { Write-Error "Operation failed: _.Exception.Message)" } finally { Write-Verbose "File operation completed." }Explanation:
trycontains code that may fail.-ErrorAction Stopconverts a cmdlet's non-terminating error into a terminating error.throwcreates a terminating error explicitly.catchhandles the error, and$_contains the current error record.finallyruns whether the operation succeeds or fails, making it useful for cleanup.
Scripts should report useful context without silently hiding errors. Specific exception types may also be handled with typed
catchblocks when different recovery actions are required. -
Question 18 of 20
Describe how PowerShell's help system is used to discover command syntax, parameters, concepts, and examples.
Model answer
PowerShell provides a built-in help system through the
Get-Helpcmdlet.Common uses include:
Get-Help Get-Processdisplays basic help for a cmdlet.Get-Help Get-Process -Detaileddisplays parameter descriptions and additional details.Get-Help Get-Process -Fulldisplays the complete local help content.Get-Help Get-Process -Examplesdisplays usage examples.Get-Help Get-Process -Parameter Nameexplains a specific parameter.Get-Help about_*lists conceptual help topics.Get-Help about_Arraysdisplays help about arrays.Get-Help Get-Process -Onlineopens online documentation when supported.
Help files can be downloaded or refreshed with
Update-Help, which may require suitable permissions and network access.Get-Commandcomplements the help system by locating commands before their exact names are known. -
Question 19 of 20
What is a PowerShell profile? Explain how profiles are located, created, edited, and used safely.
Model answer
A PowerShell profile is a script that runs automatically when a PowerShell host starts. It can configure the user's working environment by defining functions, aliases, variables, prompt customization, or module imports.
The automatic variable
$PROFILEcontains the path of the current user and current host profile. Other profile paths are available as properties, such as$PROFILE.CurrentUserAllHostsand$PROFILE.AllUsersCurrentHost.A profile can be created with:
if (-not (Test-Path $PROFILE)) { New-Item -ItemType File -Path $PROFILE -Force }It can then be opened in an editor, for example with
notepad $PROFILEon Windows. Changes usually take effect in a new PowerShell session, although the file can be loaded immediately with. $PROFILE.Profiles should remain fast, predictable, and free of untrusted code. Scripts should not depend on personal profile settings because profiles may not load in scheduled tasks, remote sessions, or automation hosts.
-
Question 20 of 20
Design a PowerShell script that reads a list of service names, checks each service, and reports its status. Explain how the script combines parameters, arrays, loops, pipelines, functions, and error handling.
Model answer
A reusable solution can accept service names as an array and return one object for each service.
Example script:
[CmdletBinding()] param( [Parameter(Mandatory)] [string[]]$ServiceName ) function Get-ServiceReport { param([string]$Name) try { $service = Get-Service -Name $Name -ErrorAction Stop [pscustomobject]@{ Name = $service.Name DisplayName = $service.DisplayName Status = $service.Status Found = $true } } catch { [pscustomobject]@{ Name = $Name DisplayName = $null Status = "Unknown" Found = $false } } } foreach ($name in $ServiceName) { Get-ServiceReport -Name $name }Concepts used:
- The script-level
paramblock accepts an array of service names. foreachprocesses every array element.- The function keeps the lookup and report-building logic reusable.
Get-Servicereturns structured service objects.tryandcatchhandle names that do not identify an installed service.[pscustomobject]produces consistent pipeline-friendly report objects.
The script could be executed as
.\ServiceReport.ps1 -ServiceName Spooler, W32Timeand its output could be piped toFormat-Table,Export-Csv, orWhere-Object. - The script-level
That's unit 5
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 5 of CSC104 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 5 of CSC104 save you a night before the exam?
Then you can help keep it free for the next batch. 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.