✅ POWERSHELL CHALLENGE SOLUTIONS

Network Applications (QHO443) - Week 10

Prepared by Babashaheer

Complete solutions with explanations

🟢 Level 1 – Warm-Up Challenges

Task 1 EASY
Service Status Reporter
# Service Status Reporter # Save as: task1.ps1 # Get service name from user $serviceName = Read-Host "Enter service name" # Get the service $service = Get-Service -Name $serviceName # Check status and display message if ($service.Status -eq "Running") { Write-Output "Service $serviceName is Running" } else { Write-Output "Service $serviceName is Stopped" }
How it works: 1. Read-Host prompts the user and stores their input
2. Get-Service -Name $serviceName retrieves the service information
3. $service.Status accesses the Status property
4. -eq "Running" checks if the status equals "Running"
5. Displays appropriate message based on the condition

Key Concepts Used:

  • Read-Host for user input
  • Get-Service cmdlet
  • If/Else conditional logic
  • Accessing object properties (.Status)
Task 2 EASY
File Counter
# File Counter # Save as: task2.ps1 # Get all .txt files $txtFiles = Get-ChildItem *.txt # Count them $count = $txtFiles.Count # Display result Write-Output "Found $count text files in this directory"
How it works: 1. Get-ChildItem *.txt gets all files ending with .txt
2. Stores the result in $txtFiles variable
3. .Count property returns the number of items
4. Displays the count using variable interpolation
Alternative One-Line Solution:
Write-Output "Found $((Get-ChildItem *.txt).Count) text files in this directory"

Key Concepts Used:

  • Get-ChildItem with wildcard filter
  • Storing command results in variables
  • .Count property
  • String interpolation with variables

🟡 Level 2 – Intermediate Challenges

Task 3 MEDIUM
CPU Monitor Alert
# CPU Monitor Alert # Save as: task3.ps1 # Get process using most CPU $topProcess = Get-Process | Sort-Object CPU -Descending | Select-Object -First 1 # Get the CPU percentage $cpuUsage = $topProcess.CPU # Check if above threshold if ($cpuUsage -gt 50) { Write-Output "⚠️ WARNING: $($topProcess.ProcessName) is using $cpuUsage% CPU!" } else { Write-Output "✓ CPU usage is normal" }
How it works: 1. Pipeline chains three operations: Get-Process → Sort → Select
2. Sort-Object CPU -Descending puts highest CPU first
3. Select-Object -First 1 gets only the top process
4. $topProcess.CPU accesses the CPU property
5. -gt 50 checks if greater than 50
6. $($topProcess.ProcessName) uses subexpression for clean output

Key Concepts Used:

  • Pipeline chaining (|)
  • Sort-Object with -Descending
  • Select-Object -First
  • Comparison operators (-gt)
  • Accessing object properties
Task 4 MEDIUM
Password Strength Checker
# Password Strength Checker # Save as: task4.ps1 # Get password from user $password = Read-Host "Enter password" # Check length $lengthOK = $password.Length -ge 12 # Check for number $hasNumber = $password -match '\d' # Evaluate both conditions if ($lengthOK -and $hasNumber) { Write-Output "✓ Strong Password!" } else { if (-not $lengthOK) { Write-Output "❌ Password must be at least 12 characters" } if (-not $hasNumber) { Write-Output "❌ Password needs a number" } }
How it works: 1. Read-Host gets password input from user
2. $password.Length -ge 12 checks if 12+ characters
3. $password -match '\d' checks if contains a digit (0-9)
4. -and operator ensures BOTH conditions are true
5. Nested if statements provide specific feedback for each failure
Security Note: For real passwords, use Read-Host -AsSecureString to hide input, though checking requirements becomes more complex.

Key Concepts Used:

  • Read-Host for input
  • .Length property
  • -match operator with regex
  • Logical operators (-and, -not)
  • Nested if/else statements
Task 5 MEDIUM
Running Services Filter
# Running Services Filter # Save as: task5.ps1 # Get all running services, select names, and sort Get-Service | Where-Object Status -eq 'Running' | Select-Object -ExpandProperty Name | Sort-Object
How it works: 1. Get-Service retrieves all services
2. Where-Object Status -eq 'Running' filters to running only
3. Select-Object -ExpandProperty Name extracts just the names (not table format)
4. Sort-Object sorts alphabetically
5. Multi-line format with backtick improves readability
Alternative (one line):
Get-Service | Where-Object Status -eq 'Running' | Select-Object -ExpandProperty Name | Sort-Object

Key Concepts Used:

  • Pipeline with multiple stages
  • Where-Object filtering
  • Select-Object -ExpandProperty (shows values, not table)
  • Sort-Object
  • Multi-line commands

🔴 Level 3 – Advanced Challenges

Task 6 HARD
System Health Check
# System Health Check # Save as: task6.ps1 # Get current date and time $timestamp = Get-Date -Format "dd/MM/yyyy HH:mm:ss" # Get all services $allServices = Get-Service $runningServices = $allServices | Where-Object Status -eq 'Running' # Get process info $allProcesses = Get-Process $topProcess = $allProcesses | Sort-Object CPU -Descending | Select-Object -First 1 # Display report Write-Output "=================================" Write-Output " SYSTEM HEALTH CHECK" Write-Output " Date: $timestamp" Write-Output "=================================" Write-Output "Services: $($runningServices.Count) Running / $($allServices.Count) Total" Write-Output "Total Processes: $($allProcesses.Count)" Write-Output "Top CPU Process: $($topProcess.ProcessName) ($($topProcess.CPU)%)" Write-Output "================================="
How it works: 1. Get-Date -Format creates formatted timestamp
2. Stores all services, then filters for running ones
3. .Count property gives totals for each
4. Finds top CPU process using Sort and Select
5. Uses $(...) subexpression syntax in strings for complex variables
6. Multiple Write-Output statements build formatted report

Key Concepts Used:

  • Get-Date with custom formatting
  • Storing and reusing variables
  • Pipeline filtering and sorting
  • Subexpression syntax $(...)
  • Building formatted output
Task 7 HARD
Large File Finder
# Large File Finder # Save as: task7.ps1 # Get user input $sizeMB = Read-Host "Enter minimum file size in MB" # Convert to bytes (PowerShell understands 1MB shorthand!) $sizeBytes = $sizeMB * 1MB # Find files larger than specified size $largeFiles = Get-ChildItem | Where-Object Length -gt $sizeBytes # Check if any files found if ($largeFiles.Count -gt 0) { Write-Output "`nFiles larger than $sizeMB MB:" foreach ($file in $largeFiles) { # Convert size to MB with 1 decimal place $fileSizeMB = [math]::Round($file.Length / 1MB, 1) Write-Output "$($file.Name) - $fileSizeMB MB" } } else { Write-Output "No files found larger than $sizeMB MB" }
How it works: 1. Read-Host gets size threshold from user
2. $sizeMB * 1MB converts MB to bytes (1MB = 1048576 bytes)
3. Where-Object Length -gt $sizeBytes filters by file size
4. if ($largeFiles.Count -gt 0) checks if any files found
5. foreach loop iterates through each file
6. [math]::Round() rounds to 1 decimal place for clean display
7. `n adds blank line for formatting

Key Concepts Used:

  • User input with Read-Host
  • PowerShell size shortcuts (1MB, 1GB, etc.)
  • Where-Object with Length property
  • Foreach loop
  • [math]::Round() for formatting
  • Conditional logic with Count check
Task 8 HARD
Service Dependency Checker
# Service Dependency Checker # Save as: task8.ps1 # Define critical services $criticalServices = @('Spooler', 'Winmgmt', 'Dhcp', 'EventLog') # Initialize counter $runningCount = 0 # Check each service foreach ($svcName in $criticalServices) { # Get service status $service = Get-Service -Name $svcName # Check if running if ($service.Status -eq 'Running') { Write-Output "✓ $svcName is OK" $runningCount++ } else { Write-Output "❌ WARNING: $svcName is STOPPED!" } } # Display summary Write-Output "-----------------------" Write-Output "Summary: $runningCount/$($criticalServices.Count) services are running"
How it works: 1. @('Service1', 'Service2') creates an array of service names
2. $runningCount = 0 initializes counter variable
3. foreach ($svcName in $criticalServices) loops through array
4. Get-Service -Name $svcName gets each service in turn
5. Checks status and displays appropriate message
6. $runningCount++ increments counter for running services
7. Summary uses counter and array's Count property
Error Handling Note: If a service doesn't exist, this will throw an error. You could wrap the Get-Service in a try/catch block for better error handling.

Key Concepts Used:

  • Arrays (@() syntax)
  • Foreach loops
  • Counter variables and increment (++)
  • Get-Service in a loop
  • If/Else logic
  • Array .Count property