Lab 8.3: System Administration with PowerShell
Learning Objectives
By the end of this lab, you will be able to:
- Create system administration scripts
- Automate maintenance tasks
- Generate system reports
- Manage users and permissions
Estimated Duration
50 minutes
Prerequisites
- Windows 10/11 VM
- Administrator rights
- Basic PowerShell knowledge
Professional Context
Administration scripts are used to:
- Automate repetitive tasks
- Maintain configuration consistency
- Generate compliance reports
- Manage user accounts
Part 1: Complete System Report
Step 1.1: Report Script
Create a script Get-SystemReport.ps1:
<#
.SYNOPSIS
Generates a complete system report
.DESCRIPTION
Collects system, network, storage, and security information
.EXAMPLE
.\Get-SystemReport.ps1
#>
param(
[string]$OutputPath = "$env:USERPROFILE\Desktop\SystemReport_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"
)
Write-Host "Generating system report..." -ForegroundColor Cyan
# CSS for the HTML report
$css = @"
<style>
body { font-family: 'Segoe UI', Arial; margin: 20px; background: #f5f5f5; }
h1 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
h2 { color: #34495e; margin-top: 30px; }
table { border-collapse: collapse; width: 100%; margin: 10px 0; background: white; }
th { background: #3498db; color: white; padding: 12px; text-align: left; }
td { padding: 10px; border: 1px solid #ddd; }
tr:nth-child(even) { background: #f9f9f9; }
.warning { color: #e74c3c; font-weight: bold; }
.ok { color: #27ae60; font-weight: bold; }
.section { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
</style>
"@
# Collect information
$computerInfo = Get-CimInstance Win32_ComputerSystem
$osInfo = Get-CimInstance Win32_OperatingSystem
$cpuInfo = Get-CimInstance Win32_Processor
$diskInfo = Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3"
$networkInfo = Get-NetAdapter | Where-Object {$_.Status -eq "Up"}
$services = Get-Service | Where-Object {$_.Status -eq "Running"}
$processes = Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 10
# Generate HTML
$html = @"
<!DOCTYPE html>
<html>
<head>
<title>System Report - $($computerInfo.Name)</title>
$css
</head>
<body>
<h1>System Report - $($computerInfo.Name)</h1>
<p>Generated on: $(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')</p>
<div class="section">
<h2>General Information</h2>
<table>
<tr><th>Property</th><th>Value</th></tr>
<tr><td>Computer Name</td><td>$($computerInfo.Name)</td></tr>
<tr><td>Domain</td><td>$($computerInfo.Domain)</td></tr>
<tr><td>Manufacturer</td><td>$($computerInfo.Manufacturer)</td></tr>
<tr><td>Model</td><td>$($computerInfo.Model)</td></tr>
<tr><td>Operating System</td><td>$($osInfo.Caption)</td></tr>
<tr><td>Version</td><td>$($osInfo.Version)</td></tr>
<tr><td>Architecture</td><td>$($osInfo.OSArchitecture)</td></tr>
<tr><td>Last Boot</td><td>$($osInfo.LastBootUpTime)</td></tr>
</table>
</div>
<div class="section">
<h2>Processor</h2>
<table>
<tr><th>Property</th><th>Value</th></tr>
<tr><td>Name</td><td>$($cpuInfo.Name)</td></tr>
<tr><td>Cores</td><td>$($cpuInfo.NumberOfCores)</td></tr>
<tr><td>Threads</td><td>$($cpuInfo.NumberOfLogicalProcessors)</td></tr>
<tr><td>Usage</td><td>$($cpuInfo.LoadPercentage)%</td></tr>
</table>
</div>
<div class="section">
<h2>Memory</h2>
<table>
<tr><th>Property</th><th>Value</th></tr>
<tr><td>Total RAM</td><td>$([math]::Round($computerInfo.TotalPhysicalMemory/1GB, 2)) GB</td></tr>
<tr><td>Available RAM</td><td>$([math]::Round($osInfo.FreePhysicalMemory/1MB, 2)) GB</td></tr>
<tr><td>Usage</td><td>$([math]::Round((1 - $osInfo.FreePhysicalMemory*1KB/$computerInfo.TotalPhysicalMemory)*100, 1))%</td></tr>
</table>
</div>
<div class="section">
<h2>Storage</h2>
<table>
<tr><th>Disk</th><th>Size</th><th>Free</th><th>Usage</th></tr>
"@
foreach ($disk in $diskInfo) {
$percentUsed = [math]::Round((1 - $disk.FreeSpace/$disk.Size)*100, 1)
$statusClass = if ($percentUsed -gt 90) { "warning" } else { "ok" }
$html += @"
<tr>
<td>$($disk.DeviceID)</td>
<td>$([math]::Round($disk.Size/1GB, 2)) GB</td>
<td>$([math]::Round($disk.FreeSpace/1GB, 2)) GB</td>
<td class="$statusClass">$percentUsed%</td>
</tr>
"@
}
$html += @"
</table>
</div>
<div class="section">
<h2>Network</h2>
<table>
<tr><th>Adapter</th><th>Status</th><th>Speed</th></tr>
"@
foreach ($adapter in $networkInfo) {
$html += @"
<tr>
<td>$($adapter.Name)</td>
<td class="ok">$($adapter.Status)</td>
<td>$([math]::Round($adapter.LinkSpeed/1000000, 0)) Mbps</td>
</tr>
"@
}
$html += @"
</table>
</div>
<div class="section">
<h2>Top 10 Processes (Memory)</h2>
<table>
<tr><th>Process</th><th>PID</th><th>Memory</th><th>CPU (s)</th></tr>
"@
foreach ($proc in $processes) {
$html += @"
<tr>
<td>$($proc.Name)</td>
<td>$($proc.Id)</td>
<td>$([math]::Round($proc.WorkingSet64/1MB, 2)) MB</td>
<td>$([math]::Round($proc.CPU, 2))</td>
</tr>
"@
}
$html += @"
</table>
</div>
<div class="section">
<h2>Running Services ($($services.Count))</h2>
<p>Total running services: $($services.Count)</p>
</div>
</body>
</html>
"@
# Save
$html | Out-File $OutputPath -Encoding UTF8
Write-Host "Report saved: $OutputPath" -ForegroundColor Green
# Open the report
Start-Process $OutputPath
Step 1.2: Run the Script
.\Get-SystemReport.ps1
Question 1: What information do you find most useful in this report?
Part 2: User Management
Step 2.1: User Management Script
# Local user management script
function Get-LocalUserReport {
Write-Host "=== LOCAL USER REPORT ===" -ForegroundColor Cyan
Get-LocalUser | ForEach-Object {
$user = $_
$groups = Get-LocalGroup | Where-Object {
(Get-LocalGroupMember $_.Name -ErrorAction SilentlyContinue).Name -contains "$env:COMPUTERNAME\$($user.Name)"
}
[PSCustomObject]@{
Name = $user.Name
Active = $user.Enabled
LastLogin = $user.LastLogon
PasswordExpire = $user.PasswordExpires
Groups = ($groups.Name -join ", ")
}
} | Format-Table -AutoSize
}
function New-StandardUser {
param(
[Parameter(Mandatory)]
[string]$Username,
[Parameter(Mandatory)]
[SecureString]$Password,
[string]$Description = "Standard user"
)
try {
New-LocalUser -Name $Username -Password $Password -Description $Description -ErrorAction Stop
Add-LocalGroupMember -Group "Users" -Member $Username
Write-Host "[OK] User $Username created" -ForegroundColor Green
} catch {
Write-Host "[ERROR] $($_.Exception.Message)" -ForegroundColor Red
}
}
function Remove-UserCompletely {
param(
[Parameter(Mandatory)]
[string]$Username
)
$confirm = Read-Host "Delete user $Username and their profile? (Y/N)"
if ($confirm -eq "Y") {
try {
# Remove user
Remove-LocalUser -Name $Username -ErrorAction Stop
# Remove profile
$profilePath = "C:\Users\$Username"
if (Test-Path $profilePath) {
Remove-Item $profilePath -Recurse -Force
}
Write-Host "[OK] User and profile deleted" -ForegroundColor Green
} catch {
Write-Host "[ERROR] $($_.Exception.Message)" -ForegroundColor Red
}
}
}
# Menu
Write-Host @"
USER MANAGEMENT
========================
1. Display user report
2. Create a standard user
3. Delete a user
4. Exit
"@
$choice = Read-Host "Choice"
switch ($choice) {
"1" { Get-LocalUserReport }
"2" {
$name = Read-Host "Username"
$pass = Read-Host "Password" -AsSecureString
New-StandardUser -Username $name -Password $pass
}
"3" {
$name = Read-Host "Username to delete"
Remove-UserCompletely -Username $name
}
}
Part 3: Maintenance Script
Step 3.1: Automated Maintenance
<#
.SYNOPSIS
Automated system maintenance script
#>
param(
[switch]$CleanTemp,
[switch]$CheckDisk,
[switch]$UpdateHelp,
[switch]$All
)
$ErrorActionPreference = "SilentlyContinue"
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$color = switch ($Level) {
"INFO" { "White" }
"SUCCESS" { "Green" }
"WARNING" { "Yellow" }
"ERROR" { "Red" }
}
Write-Host "[$timestamp] [$Level] $Message" -ForegroundColor $color
}
function Clear-TempFiles {
Write-Log "Cleaning temporary files..." "INFO"
$paths = @(
$env:TEMP,
"C:\Windows\Temp",
"C:\Windows\Prefetch"
)
$totalSize = 0
$totalFiles = 0
foreach ($path in $paths) {
if (Test-Path $path) {
$files = Get-ChildItem $path -Recurse -Force -ErrorAction SilentlyContinue
$size = ($files | Measure-Object -Property Length -Sum).Sum
$count = $files.Count
Remove-Item "$path\*" -Recurse -Force -ErrorAction SilentlyContinue
$totalSize += $size
$totalFiles += $count
}
}
Write-Log "Cleaned: $totalFiles files, $([math]::Round($totalSize/1MB, 2)) MB" "SUCCESS"
}
function Test-DiskHealth {
Write-Log "Checking disk health..." "INFO"
Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object {
$disk = $_
$percentFree = [math]::Round($disk.FreeSpace / $disk.Size * 100, 1)
if ($percentFree -lt 10) {
Write-Log "ALERT: Disk $($disk.DeviceID) - Only $percentFree% free!" "ERROR"
} elseif ($percentFree -lt 20) {
Write-Log "Warning: Disk $($disk.DeviceID) - $percentFree% free" "WARNING"
} else {
Write-Log "Disk $($disk.DeviceID) - $percentFree% free" "SUCCESS"
}
}
}
function Update-PSHelp {
Write-Log "Updating PowerShell help..." "INFO"
try {
Update-Help -Force -ErrorAction Stop
Write-Log "Help updated" "SUCCESS"
} catch {
Write-Log "Help update failed: $($_.Exception.Message)" "WARNING"
}
}
function Get-SystemHealth {
Write-Log "Checking system health..." "INFO"
# CPU
$cpu = (Get-CimInstance Win32_Processor).LoadPercentage
if ($cpu -gt 90) {
Write-Log "CPU: $cpu% (CRITICAL)" "ERROR"
} elseif ($cpu -gt 70) {
Write-Log "CPU: $cpu% (High)" "WARNING"
} else {
Write-Log "CPU: $cpu% (Normal)" "SUCCESS"
}
# RAM
$os = Get-CimInstance Win32_OperatingSystem
$ramUsed = [math]::Round((1 - $os.FreePhysicalMemory*1KB / (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory) * 100, 1)
if ($ramUsed -gt 90) {
Write-Log "RAM: $ramUsed% used (CRITICAL)" "ERROR"
} elseif ($ramUsed -gt 80) {
Write-Log "RAM: $ramUsed% used (High)" "WARNING"
} else {
Write-Log "RAM: $ramUsed% used (Normal)" "SUCCESS"
}
# Critical services
$criticalServices = @("wuauserv", "EventLog", "Dnscache")
foreach ($svc in $criticalServices) {
$service = Get-Service $svc -ErrorAction SilentlyContinue
if ($service.Status -ne "Running") {
Write-Log "Service $svc is not running!" "WARNING"
}
}
}
# Execution
Write-Host @"
===============================================
SYSTEM MAINTENANCE SCRIPT
$(Get-Date -Format "dd/MM/yyyy HH:mm")
===============================================
"@ -ForegroundColor Cyan
Get-SystemHealth
if ($All -or $CleanTemp) { Clear-TempFiles }
if ($All -or $CheckDisk) { Test-DiskHealth }
if ($All -or $UpdateHelp) { Update-PSHelp }
Write-Host "`n===============================================" -ForegroundColor Cyan
Write-Log "Maintenance completed" "SUCCESS"
Step 3.2: Run Maintenance
# All tasks
.\Maintenance.ps1 -All
# Or selectively
.\Maintenance.ps1 -CleanTemp -CheckDisk
Part 4: Security Audit
Step 4.1: Audit Script
# Basic security audit
Write-Host "=== SECURITY AUDIT ===" -ForegroundColor Cyan
$findings = @()
# 1. Check Windows Defender
$defender = Get-MpComputerStatus -ErrorAction SilentlyContinue
if ($defender) {
if (-not $defender.RealTimeProtectionEnabled) {
$findings += "[CRITICAL] Real-time protection disabled"
}
if (-not $defender.AntivirusEnabled) {
$findings += "[CRITICAL] Antivirus disabled"
}
}
# 2. Check firewall
$firewall = Get-NetFirewallProfile
foreach ($profile in $firewall) {
if (-not $profile.Enabled) {
$findings += "[CRITICAL] Firewall $($profile.Name) disabled"
}
}
# 3. Check updates
$lastUpdate = (Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 1).InstalledOn
$daysSinceUpdate = (New-TimeSpan -Start $lastUpdate -End (Get-Date)).Days
if ($daysSinceUpdate -gt 30) {
$findings += "[WARNING] No update for $daysSinceUpdate days"
}
# 4. Check admin accounts
$admins = Get-LocalGroupMember -Group "Administrators"
if ($admins.Count -gt 3) {
$findings += "[WARNING] $($admins.Count) accounts in the Administrators group"
}
# 5. Check shares
$shares = Get-SmbShare | Where-Object {$_.Name -notmatch '^\$'}
if ($shares) {
$findings += "[INFO] $($shares.Count) active shares: $($shares.Name -join ', ')"
}
# Report
Write-Host "`n=== RESULTS ===" -ForegroundColor Yellow
if ($findings.Count -eq 0) {
Write-Host "[OK] No issues detected" -ForegroundColor Green
} else {
foreach ($finding in $findings) {
if ($finding -match "CRITICAL") {
Write-Host $finding -ForegroundColor Red
} elseif ($finding -match "WARNING") {
Write-Host $finding -ForegroundColor Yellow
} else {
Write-Host $finding -ForegroundColor Cyan
}
}
}
Deliverables
-
Created Scripts:
- Get-SystemReport.ps1
- User management script
- Maintenance script
- Audit script
-
Screenshots:
- Generated HTML report
- Maintenance execution
- Audit result
-
Answer to Question 1
Evaluation Criteria
| Criteria | Points |
|---|---|
| Report script | 30% |
| User management | 20% |
| Maintenance script | 30% |
| Audit script | 20% |
Lab developed as part of the Operating Systems course - MODULE 8