Unit6 - Subjective Questions
CSC104 • Practice Questions with Detailed Answers
Explain the concept of PowerShell Modules. How do they differ from standard scripts, and what command is used to load them into the current session?
A PowerShell Module is a package that contains PowerShell members, such as cmdlets, providers, functions, variables, and aliases.
Key differences from standard scripts:
- Organization: Modules are used to organize code into reusable units, whereas scripts (
.ps1) are usually standalone execution files. - Portability: Modules can be easily shared and installed on different systems.
- Scope: Modules run in their own scope, preventing variable collision with the global scope.
File Extensions:
.psm1: Script module file..psd1: Module manifest file.
Loading Modules:
To load a module, use the command:
Import-Module -Name <ModuleName>
Describe the process of handling CSV files in PowerShell. Provide syntax examples for importing data from a CSV and exporting data to a CSV.
PowerShell handles CSV (Comma Separated Values) files by converting the text data into custom PowerShell objects (PSCustomObject) where the column headers become the property names.
1. Importing CSV:
The Import-Csv cmdlet creates objects from the CSV file.
Syntax:
$data = Import-Csv -Path "C:\path\to\file.csv"
2. Exporting CSV:
The Export-Csv cmdlet converts objects into a series of CSV strings and saves them to a file.
Syntax:
Get-Process | Export-Csv -Path "C:\path\to\processes.csv" -NoTypeInformation
Note: The -NoTypeInformation switch is often used to prevent the addition of the type information header #TYPE to the file.
Distinguish between ConvertTo-Json and ConvertFrom-Json in the context of data serialization.
These two cmdlets are used for handling JSON (JavaScript Object Notation) data, which is essential for working with APIs and configuration files.
1. ConvertTo-Json:
- Function: Converts a .NET object (or PowerShell object) into a JSON-formatted string.
- Use Case: Sending data to a REST API or saving configuration to a file.
- Example:
powershell
$user = @{ Name = "John"; ID = 101 }
user | ConvertTo-Json
2. ConvertFrom-Json:
- Function: Converts a JSON-formatted string into a custom PowerShell object (
PSCustomObject). - Use Case: Parsing the response body from a web API or reading a config file.
- Example:
powershell
json | ConvertFrom-Json
How does PowerShell handle XML data? Explain how to load an XML file and navigate its nodes.
PowerShell creates a Document Object Model (DOM) of XML data, allowing users to navigate nodes as if they were object properties.
Loading XML:
You can cast the content of a file to the [xml] type accelerator.
powershell
[xml]$xmlData = Get-Content -Path "C:\config.xml"
Navigating Nodes:
Once loaded, the XML elements become properties. Dot notation is used to traverse the hierarchy.
Example: If the XML structure is <Settings><Theme>Dark</Theme></Settings>:
powershell
Accessing the value
xmlData.Settings.Theme
PowerShell also allows the use of XPath with the Select-Xml cmdlet for more complex queries.
Write a logic flow or pseudo-code for creating a text-based interactive menu using PowerShell loops and Read-Host.
An interactive menu typically uses a do-while or while loop to keep the menu active until the user chooses to exit.
Logic Flow / Structure:
- Start Loop: Initiate a
doloop. - Clear Screen: Use
Clear-Hostto make the menu neat. - Display Options: Write lines describing the choices (e.g., "1. Start Service", "2. Stop Service", "Q. Quit").
- Capture Input: Use
$selection = Read-Host "Enter choice". - Process Input: Use a
Switchstatement orIf-Elseblock to handle the input.- Case 1: Run Start logic.
- Case 2: Run Stop logic.
- Case Q: Set a flag to break the loop.
- Pause: Optionally add
PauseorStart-Sleepso the user can read the output. - End Loop: Check the
whilecondition (e.g.,while ($selection -ne 'Q')).
Explain how to manage Windows Services using PowerShell. Include commands to check status, start, stop, and restart a service.
PowerShell provides the *-Service cmdlets to manage background services on Windows.
Key Cmdlets:
- Get-Service: Retrieves the status of services.
Get-Service -Name "Spooler"
- Start-Service: Starts a stopped service.
Start-Service -Name "Spooler"
- Stop-Service: Stops a running service.
Stop-Service -Name "Spooler" -Force(Force is needed if it has dependent services).
- Restart-Service: Stops and then starts a service.
Restart-Service -Name "Spooler"
- Set-Service: Changes service properties (e.g., StartupType).
Set-Service -Name "Spooler" -StartupType Automatic
How can you identify and stop a high-resource consuming Process using PowerShell?
To identify and stop a process consuming high resources (e.g., CPU or Memory), follow these steps:
1. Identify the Process:
Use Get-Process and sort by the resource property (e.g., CPU or WorkingSet for memory).
Example (Top 5 Memory consumers):
powershell
Get-Process | Sort-Object -Property WorkingSet -Descending | Select-Object -First 5
2. Stop the Process:
Pipe the object to Stop-Process or use the command directly with the Name or ID.
Example (Stop by Name):
powershell
Stop-Process -Name "Notepad" -Force
Example (Stop by ID identified in step 1):
powershell
Stop-Process -Id 1234 -Force
Describe how PowerShell interacts with the Windows Registry. How does the Registry Provider work?
PowerShell interacts with the Windows Registry via a Provider. The Registry Provider creates a drive-like interface (PSDrive) for the registry hives, allowing you to navigate and manipulate keys and values as if they were files and folders.
Registry Drives:
HKLM:maps toHKEY_LOCAL_MACHINEHKCU:maps toHKEY_CURRENT_USER
Common Operations:
- Navigation:
Set-Location HKCU:\Software - Create Key (Folder):
New-Item -Path .\MyApp -ItemType Directory - Create/Modify Value:
New-ItemProperty -Path .\MyApp -Name "Version" -Value "1.0" -PropertyType String - Read Value:
Get-ItemProperty -Path .\MyApp -Name "Version" - Delete:
Remove-ItemorRemove-ItemProperty.
This abstraction makes registry editing scriptable and consistent with file system operations.
Discuss the prerequisites and cmdlets used for managing Active Directory (AD) users in PowerShell.
To manage Active Directory via PowerShell, the Active Directory module must be installed (part of RSAT - Remote Server Administration Tools).
Prerequisites:
- RSAT installed on the client machine.
- User must have appropriate administrative privileges (e.g., Domain Admin or delegated rights).
- Connectivity to the Domain Controller.
Key User Management Cmdlets:
- New-ADUser: Creates a new user.
- Example:
New-ADUser -Name "JohnDoe" -AccountPassword true
- Example:
- Get-ADUser: Retrieves user details.
- Example:
Get-ADUser -Identity "JohnDoe" -Properties *
- Example:
- Set-ADUser: Modifies existing user attributes.
- Example:
Set-ADUser -Identity "JohnDoe" -Department "IT"
- Example:
- Remove-ADUser: Deletes a user account.
- Unlock-ADAccount: Unlocks a locked user account.
What is PowerShell Remoting? Explain the difference between Enter-PSSession and Invoke-Command.
PowerShell Remoting allows execution of PowerShell commands on remote systems using the WS-Management (WS-MAN) protocol. It relies on the Windows Remote Management (WinRM) service.
Enter-PSSession (1-to-1 Interactive):
- Purpose: Starts an interactive session with a single remote computer.
- Experience: The prompt changes to
[ComputerName]: PS ..., and commands run directly on the remote machine. - Use Case: Troubleshooting a specific server manually.
Invoke-Command (1-to-Many Automation):
- Purpose: Runs a command or script block on one or multiple computers simultaneously.
- Experience: It runs non-interactively and returns the results to the local console.
- Use Case: Deploying settings or gathering info from 100 servers at once.
- Syntax:
Invoke-Command -ComputerName Server1, Server2 -ScriptBlock { Get-Service Spooler }
Explain the security considerations when enabling PowerShell Remoting and the command used to enable it.
Enabling Remoting:
The primary command to configure a system to receive remote commands is:
Enable-PSRemoting -Force
Actions performed by this command:
- Starts the WinRM service.
- Sets the WinRM service to start automatically.
- Creates a listener on HTTP (port 5985) or HTTPS (port 5986).
- Configures Windows Firewall exceptions.
Security Considerations:
- Authentication: By default, it uses Kerberos (domain) which is secure. Using Basic authentication requires SSL/HTTPS to be safe.
- Administrator Access: By default, only Administrators can connect remotely.
- TrustedHosts: In non-domain environments, modifying the
TrustedHostslist allows connections, but care must be taken not to trust*(all) in high-security zones. - Double Hop Issue: Passing credentials from a remote machine to a second remote machine is blocked by default (requires CredSSP or constrained delegation).
Differentiate between PowerShell Jobs and standard execution. List the commands to manage jobs.
Standard Execution: Runs in the foreground. The console is blocked (locked) until the command finishes. If the command takes an hour, the user cannot use that shell for an hour.
PowerShell Jobs (Background Jobs): Runs asynchronously in the background on a separate thread/process. The console is immediately returned to the user, allowing them to continue working while the task runs.
Commands to Manage Jobs:
- Start-Job: Initiates a background job.
Start-Job -ScriptBlock { Get-ChildItem -Recurse }
- Get-Job: Lists current jobs and their status (Running, Completed, Failed).
- Receive-Job: Retrieves the output/results of the job.
Receive-Job -Id 1 -Keep(Use-Keepto retain data after reading).
- Stop-Job: Stops a running job.
- Remove-Job: Deletes the job object from memory.
How can you automate the creation of Scheduled Tasks using PowerShell?
PowerShell creates scheduled tasks using cmdlets introduced in PowerShell 3.0 (ScheduledTasks module). The process involves defining an Action, a Trigger, and then registering the task.
Steps:
-
Create Action: Define what the task does (run a program/script).
powershell
$action = New-ScheduledTaskAction -Execute "Powershell.exe" -Argument "-File C:\Scripts\Backup.ps1" -
Create Trigger: Define when the task runs (e.g., daily, at startup).
powershell
$trigger = New-ScheduledTaskTrigger -Daily -At 3am -
Register Task: Combine action and trigger to create the task in the system.
powershell
Register-ScheduledTask -Action trigger -TaskName "DailyBackup" -User "System"
Define an Advanced Function in PowerShell. What is the significance of [CmdletBinding()]?
An Advanced Function (often called a "Script Cmdlet") is a PowerShell function that mimics the behavior of a compiled C# cmdlet. It behaves like a native PowerShell command.
Significance of [CmdletBinding()]:
Placing the [CmdletBinding()] attribute before the param() block upgrades a standard function to an advanced function. It enables:
- Common Parameters: Automatically adds support for parameters like
-Verbose,-Debug,-ErrorAction, and-WhatIf. - Input Processing: Allows the function to process pipeline input effectively.
- WhatIf / Confirm: Supports
-WhatIf(dry run) and-Confirm(prompt user) scenarios ifSupportsShouldProcess=$trueis defined.
Structure Example:
powershell
function Get-MyData {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Name
)
Code here
}
Explain Parameter Validation attributes in PowerShell functions with examples.
Parameter validation attributes ensure that the data passed to a function meets specific criteria before the code inside the function executes. This reduces errors and the need for manual if statements.
Common Attributes:
-
[ValidateSet()]: Restricts input to a specific set of strings.
powershell
[ValidateSet("Low", "Medium", "High")]
[string]$Priority -
[ValidateRange()]: Ensures a number falls within a min/max range.
powershell
[ValidateRange(1, 100)]
[int]$Age -
[ValidateNotNullOrEmpty()]: Ensures the parameter is not null and not an empty string.
-
[ValidatePattern()]: Uses Regex to validate the format (e.g., email address).
-
[ValidateScript()]: Runs a script block; if it returns
$true, the input is valid.
powershell
[ValidateScript({ Test-Path $_ })] # Checks if file path exists
[string]$Path
What approaches are available for GUI Scripting in PowerShell? Briefly explain the Windows Forms approach.
PowerShell can generate Graphical User Interfaces (GUIs) to make scripts more user-friendly. The two main approaches are:
- Windows Forms (WinForms): Older, simpler, based on the .NET
System.Windows.Formsnamespace. - WPF (Windows Presentation Foundation): Newer, uses XAML for design, more flexible styling.
Windows Forms Approach:
You must load the assembly and create objects for the form and controls.
- Load Assembly:
Add-Type -AssemblyName System.Windows.Forms - Create Form:
$form = New-Object System.Windows.Forms.Form - Add Controls: Create buttons/textboxes (
form.Controls.Add($btn)). - Show Form:
$form.ShowDialog()to display the window.
Design a conceptual automation script for User Management (User Onboarding). What logic steps should the script include?
An automated user onboarding script typically takes a CSV input (from HR) and creates the necessary IT resources.
Logic Steps:
- Import Data: Read user details from a CSV file (
Import-Csv). - Loop Through Users: Process each row using
Foreach-Object. - Validation: Check if the user already exists in Active Directory (
Get-ADUser). If yes, log an error or skip. - Password Generation: Generate a temporary secure password.
- Create AD Account: Use
New-ADUserwith details (Name, Dept, Title, Path). - Create Home Directory: Create a folder on the file server and assign permissions (ACLs) for the new user.
- Add to Groups: Add the user to default security groups based on Department (
Add-ADGroupMember). - Email Enable: If using on-prem Exchange, enable the mailbox.
- Reporting/Logging: Log the success/failure to a text file and export the temporary credentials to a secure CSV for the manager.
How can PowerShell be used for System Monitoring? specific to monitoring disk space.
PowerShell can query WMI/CIM classes to monitor system resources like disk space, CPU, or memory.
Monitoring Disk Space:
The script uses Get-CimInstance (or Get-WmiObject) to query the Win32_LogicalDisk class.
Script Logic:
- Query: Get disks where
DriveType = 3(Local Disk).
_.DriveType -eq 3 } - Calculate: Iterate through disks and calculate free space percentage.
Formula: - Alert: If the percentage is below a threshold (e.g., 10%), trigger an action.
- Action: The action could be sending an email (
Send-MailMessage), writing to the Event Log (Write-EventLog), or displaying a warning.
Describe how to automate Log Analysis using PowerShell to find specific error events.
PowerShell automates log analysis using the Get-EventLog or Get-WinEvent cmdlets.
Scenario: Finding recent Critical Errors.
- Get-EventLog: Use this for standard logs (System, Application, Security).
- Filtering: Filter by LogName, EntryType, and Time.
Example Script Logic:
powershell
Get errors from the System log in the last 24 hours
$errors = Get-EventLog -LogName System -EntryType Error -After (Get-Date).AddDays(-1)
Group by Source to see which application is crashing most
errors | Group-Object Source | Sort-Object Count -Descending
Export to CSV for review
$summary | Export-Csv "C:\Logs\DailyErrorReport.csv"
This automation transforms thousands of raw log entries into a summarized report.
Discuss the role of PowerShell in Deployment Tasks. How can a script deploy software to multiple remote machines?
PowerShell is a key tool in DevOps and IT Ops for deploying software, configurations, or patches across environments.
Mechanism for Remote Deployment:
-
Repository: The installer (MSI/EXE) must be in a shared network location accessible by remote machines, or copied to them.
-
Copy-Item: Copy the installer to the destination nodes.
Copy-Item -Path "C:\Installer.msi" -Destination "\\Server01\C$\Temp" -
Invoke-Command: Execute the installation remotely.
powershell
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock {
Start-Process "msiexec.exe" -ArgumentList "/i C:\Temp\Installer.msi /quiet /norestart" -Wait
} -
Verification: The script should verify the installation (e.g., checking registry keys or
Get-Package) and report success or failure.