Unit 5: PowerShell Basics and Core Concepts - Subjective Questions
CSC104 — It Fundamentals • Practice Questions with Detailed Answers
20 questions
Define PowerShell and explain how it differs from a traditional command-line shell.
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.
Compare the PowerShell Console and PowerShell ISE. Describe a suitable use case for each.
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.
Describe the steps required to create, save, and execute a PowerShell script file. Also explain the purpose of the execution policy.
A PowerShell script is a text file with the .ps1 extension.
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, and Bypass. The current policies can be inspected with Get-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.
Explain how variables are declared and used in PowerShell. Discuss variable naming, data types, and type casting with examples.
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.
Explain how PowerShell accepts user input. Write and explain a script that reads two numbers and displays their sum.
PowerShell commonly accepts interactive input through the Read-Host cmdlet. Since Read-Host normally 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.
Distinguish between single-line comments, block comments, and comment-based help in PowerShell.
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.
What is a PowerShell cmdlet? Explain its naming convention, parameters, aliases, and command-discovery facilities.
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-Noun naming 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-Process retrieves process objects. Parameters modify command behavior, as in Get-Process -Name powershell. Switch parameters represent Boolean choices, such as -Force.
An alias is an alternative short name for a command. For example, gci is an alias for Get-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.
Explain the PowerShell pipeline and demonstrate how objects move through a multi-stage pipeline.
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, CPU
Pipeline 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.
Classify the major operators available in PowerShell and provide examples of their use.
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.
Describe the syntax and working of if, elseif, and else statements. Write a PowerShell example that assigns a grade from a numeric score.
Conditional statements execute different blocks of code according to whether Boolean conditions are true or false. PowerShell evaluates if first, then each elseif in order, and finally else if 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.
Explain the switch statement in PowerShell. How can it be used for exact, wildcard, and regular-expression matching?
The switch statement compares one or more input values against several conditions. It is often clearer than a long chain of elseif statements.
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. Unlike switch in some languages, PowerShell may execute multiple matching clauses. The break statement can stop further matching when only one result is required.
Compare the for, foreach, while, and do loops in PowerShell. State when each loop is appropriate.
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).
break exits a loop immediately, whereas continue skips the remainder of the current iteration. A loop must update the state used in its condition; otherwise, it may become an infinite loop.
Explain arrays in PowerShell. Describe how to create, access, modify, iterate over, and inspect an array.
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, and Sort-Object can be used to search, filter, and arrange their elements.
What is a PowerShell hashtable? Explain how to create, access, update, remove, and enumerate key-value pairs.
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.
Describe how functions are defined in PowerShell. Write an advanced function with a parameter, validation, pipeline support, and a return value.
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-Square
Explanation:
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.
Explain variable scope in PowerShell. Distinguish among global, script, local, and private scopes.
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.
Explain basic error handling in PowerShell using try, catch, finally, throw, and -ErrorAction.
PowerShell distinguishes between terminating and non-terminating errors. A try block 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 catch blocks when different recovery actions are required.
Describe how PowerShell's help system is used to discover command syntax, parameters, concepts, and examples.
PowerShell provides a built-in help system through the Get-Help cmdlet.
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-Command complements the help system by locating commands before their exact names are known.
What is a PowerShell profile? Explain how profiles are located, created, edited, and used safely.
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 $PROFILE contains the path of the current user and current host profile. Other profile paths are available as properties, such as $PROFILE.CurrentUserAllHosts and $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 $PROFILE on 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.
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.
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, W32Time and its output could be piped to Format-Table, Export-Csv, or Where-Object.
Define PowerShell and explain how it differs from a traditional command-line shell.
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.
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 →