Unit 6 - Notes
CSC104
Unit 6: Advanced PowerShell and Automation
1. Modules and Advanced Functions
PowerShell Modules
A module is a package that contains PowerShell members, such as cmdlets, providers, functions, workflows, variables, and aliases. It allows for the organization and distribution of code.
- File Types:
- .psm1 (Script Module): A PowerShell script containing functions and variables.
- .psd1 (Module Manifest): A hash table describing metadata (version, author, dependencies) about the module.
- .dll (Binary Module): Compiled code (usually C#) providing cmdlets.
- Key Cmdlets:
Get-Module -ListAvailable: Lists modules installed on the system.Import-Module <Name>: Loads a module into the current session.Install-Module <Name>: Downloads modules from the PowerShell Gallery (requires PowerShellGet).$env:PSModulePath: The environment variable defining where PowerShell looks for modules.
Advanced Functions
Standard functions can be converted into "Advanced Functions" (or Script Cmdlets) to behave like native compiled cmdlets.
- CmdletBinding Attribute: Placing
[CmdletBinding()]before theParam()block enables common parameters (e.g.,-Verbose,-Debug,-ErrorAction,-WhatIf,-Confirm). - Parameter Validation: Restricts input to ensure script stability.
Common Validation Attributes:
[Parameter(Mandatory=$true)]: User must provide a value.[ValidateSet("Option1", "Option2")]: Input must match a specific list.[ValidateRange(1, 100)]: Input must be a number within bounds.[ValidateNotNullOrEmpty()]: Input cannot be null or an empty string.[ValidateScript({$_ -match "@domain.com"})]: Custom logic validation.
Example: Advanced Function
function New-CustomUser {
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
[Parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[string]$UserName,
[Parameter(Mandatory=$false)]
[ValidateSet("HR", "IT", "Sales")]
[string]$Department = "HR"
)
Process {
if ($PSCmdlet.ShouldProcess($UserName, "Create User")) {
Write-Output "Creating user $UserName in $Department"
}
}
}
2. File Handling (CSV, JSON, XML)
PowerShell treats data as objects. File handling involves serializing (converting objects to text) and deserializing (text to objects).
CSV (Comma Separated Values)
Ideal for flat data structures and Excel compatibility.
- Import-Csv: Converts a CSV file into custom PowerShell objects (PSCustomObject). Headers become property names.
- Export-Csv: Converts objects to a CSV file.
- Tip: Always use
-NoTypeInformationto remove the#TYPEheader in the output file.
- Tip: Always use
JSON (JavaScript Object Notation)
Ideal for web APIs, NoSQL databases, and hierarchical configuration files.
- ConvertTo-Json: Converts an object to a JSON string.
- Depth: By default, creates JSON 2 levels deep. Use
-Depthparameter for complex objects.
- Depth: By default, creates JSON 2 levels deep. Use
- ConvertFrom-Json: Converts a JSON string/file into a PSCustomObject.
XML (eXtensible Markup Language)
Older standard, highly structured, strict syntax.
- Reading XML:
[xml]$xmlData = Get-Content config.xml: Casts content directly to an XML object.Select-Xml: Uses XPath queries to find specific nodes.
- Traversing XML: Nodes are accessed via dot notation (e.g.,
$xmlData.Configuration.Server.IP).
Comparison Example:
# Export Processes to CSV
Get-Process | Select-Object Name, Id, CPU | Export-Csv -Path "procs.csv" -NoTypeInformation
# Convert a Hash Table to JSON
$config = @{ Server = "Web01"; Port = 8080; SSL = $true }
$jsonPayload = $config | ConvertTo-Json
3. Menus and Prompts
Automation often requires user input or selection.
Basic Input
- Read-Host: Pauses execution to accept user string input.
- Secure strings (passwords) use
-AsSecureString.
- Secure strings (passwords) use
Creating Text-Based Menus
Menus are typically constructed using a Do-While loop containing a Switch statement.
Example Menu Template:
$quit = $false
Do {
Clear-Host
Write-Host "=== System Management Menu ===" -ForegroundColor Cyan
Write-Host "1. Show Services"
Write-Host "2. Show Processes"
Write-Host "Q. Quit"
$selection = Read-Host "Please make a selection"
Switch ($selection) {
'1' { Get-Service | Select-Object -First 10; Pause }
'2' { Get-Process | Select-Object -First 10; Pause }
'Q' { $quit = $true }
Default { Write-Warning "Invalid selection" }
}
} While ($quit -eq $false)
4. System Tasks: Services, Processes, Registry
Service Management
- Cmdlets:
Get-Service,Start-Service,Stop-Service,Restart-Service,Set-Service. - Usage: Can change startup types (Automatic/Manual/Disabled) and check status (Running/Stopped).
- Note: Requires elevated privileges (Run as Administrator) to change state.
Process Management
- Cmdlets:
Get-Process,Stop-Process,Start-Process. - Usage:
Stop-Process -Name notepad -Force: Kills a process.Start-Process: Can launch executables with arguments (-ArgumentList) and window styles (-WindowStyle Hidden).
Registry Management
PowerShell maps the Registry as a drive (HKLM:, HKCU:).
- Navigation:
cd HKLM:\Software - Get-ItemProperty: Reads specific registry values.
- Set-ItemProperty: Modifies or adds registry values.
- New-Item: Creates new Registry Keys (folders).
- Remove-ItemProperty: Deletes a registry value.
# Disable IPv6 via Registry (Example)
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters" -Name "DisabledComponents" -Value 0xFF -Type DWord
5. Active Directory (AD) Automation
Requires the Active Directory module (part of RSAT).
User Management
- Get-ADUser: Retrieves user objects.
- Important: Use
-Properties *or specify properties (e.g.,LastLogonDate) as not all are returned by default.
- Important: Use
- New-ADUser: Creates a new user. Requires secure string for password.
- Set-ADUser: Modifies attributes of an existing user.
Group Management
- Get-ADGroup / New-ADGroup: Manage group objects.
- Add-ADGroupMember / Remove-ADGroupMember: Manage membership.
Filtering Performance
- Server-side filtering (
-Filter): Efficient. The AD controller filters data before sending it to PowerShell.Get-ADUser -Filter "Department -eq 'IT'"
- Client-side filtering (
Where-Object): Inefficient. Retrieves all users, then filters locally.Get-ADUser -Filter * | Where-Object {$_.Department -eq 'IT'}(Avoid for large directories).
6. PowerShell Remoting
Allows execution of commands on remote systems via WS-Management (WinRM).
Configuration
- Enable-PSRemoting: Configures the computer to receive remote commands (starts WinRM service, sets firewall rules).
Usage Methods
- Interactive Session (1-to-1):
Enter-PSSession -ComputerName <ServerName>- Changes the prompt to
[ServerName]: PS C:\>. Used for manual troubleshooting.
- Remote Command Execution (1-to-Many):
Invoke-Command -ComputerName <Server1>,<Server2> -ScriptBlock { Get-Service Spooler }- Runs in parallel. Returns objects to the local console with a
PSComputerNameproperty.
Credentials
Use Get-Credential to store credentials in a variable and pass them to -Credential parameter for cross-domain or privileged access.
7. Jobs and Scheduled Tasks
PowerShell Jobs (Background Jobs)
Jobs allow scripts to run asynchronously (in the background) without blocking the console.
- Start-Job: Starts a background job.
$job = Start-Job -ScriptBlock { Get-ChildItem C:\ -Recurse }
- Get-Job: Checks the status (Running, Completed, Failed).
- Receive-Job: Retrieves the output.
- Use
-Keepto prevent the data from being deleted after reading.
- Use
- Remove-Job: Deletes the job from memory.
Scheduled Tasks (Task Scheduler)
Persistent tasks that survive reboots.
- Cmdlets (Module: ScheduledTasks):
New-ScheduledTaskAction: What to run (program/script).New-ScheduledTaskTrigger: When to run (AtStartup, Daily, AtLogon).Register-ScheduledTask: Creates the task in Windows Task Scheduler.
- Principal: Defines the user account context (
New-ScheduledTaskPrincipal).
8. GUI Scripting (Windows Forms)
PowerShell can utilize .NET frameworks to create graphical user interfaces.
Windows Forms (WinForms)
- Load Assembly:
Add-Type -AssemblyName System.Windows.Forms - Key Objects:
System.Windows.Forms.Form: The main window.System.Windows.Forms.Button: Clickable button.System.Windows.Forms.TextBox: Input field.System.Windows.Forms.Label: Text display.
- Event Handling: Define what happens on interaction.
$Button.Add_Click({ Write-Host "Clicked!" })
- Displaying:
$Form.ShowDialog()
Basic Form Example:
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$form.Text = "My Tool"
$btn = New-Object System.Windows.Forms.Button
$btn.Text = "Click Me"
$btn.Location = New-Object System.Drawing.Point(100,100)
$btn.Add_Click({ [System.Windows.Forms.MessageBox]::Show("Hello World") })
$form.Controls.Add($btn)
$form.ShowDialog()
9. Automation Scripts: Practical Scenarios
Scenario A: User Management (Onboarding)
Logic Flow:
- Import data from CSV (
Import-Csv). - Loop through each row (
ForEach-Object). - Generate a temporary password.
- Create AD User (
New-ADUser). - Add to groups based on department property.
- Create Home Directory (
New-Item -Type Directory). - Set NTFS permissions (ACLs).
Scenario B: Log Management (Housekeeping)
Logic Flow:
- Define log path and retention period (e.g., 30 days).
Get-ChildItemto find files matching filter (*.log).- Filter by date (
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) }). - Archive files (Compress) or Remove files (
Remove-Item). - Write result to a master operational log.
Scenario C: System Monitoring
Logic Flow:
- Get disk space:
Get-VolumeorGet-WmiObject Win32_LogicalDisk. - Calculate percentage free.
- Check threshold (e.g., if free space < 10%).
- If critical, send alert using
Send-MailMessage(SMTP) or write to Event Log (Write-EventLog).
Scenario D: Deployment Tasks
Logic Flow:
- Define list of target servers.
- Copy installer file to targets using
Copy-Item -ToSession. - Use
Invoke-Commandto run the installer silently (e.g.,msiexec /i app.msi /qn). - Verify installation (check Registry or
Get-Package).