Voiced by Amazon Polly |
PowerShell is a powerful scripting language designed specifically for Windows system administration. It provides a robust framework for automating repetitive tasks, managing servers, and streamlining IT workflows. In this blog, we will explore practical PowerShell scripts that leverage ForEach, For, If-Else, Switch, and While loops to handle common administrative tasks. These examples are perfect for both beginners and seasoned admins looking to sharpen their scripting skills.
Enhance Your Productivity with Microsoft Copilot
- Effortless Integration
- AI-Powered Assistance
Why Use PowerShell for Windows Administration?
PowerShell is ideal for managing Windows environments because it:
- Provides direct access to the Windows Management Instrumentation (WMI) and .NET classes.
- Supports advanced automation through scripts and functions.
- Integrates seamlessly with Active Directory and Azure.
- Allows for powerful task automation using loops and conditionals.
1. Disk Space Monitoring (ForEach and If-Else)
Checking the free space on multiple drives is a routine task for system administrators. This script iterates through each drive on a server, reporting available space:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$drives = Get-PSDrive -PSProvider FileSystem foreach ($drive in $drives) { $freeSpaceGB = [math]::Round($drive.Free / 1GB, 2) if ($freeSpaceGB -lt 10) { Write-Output "Warning: Drive $($drive.Name) is low on space ($freeSpaceGB GB free)." } else { Write-Output "Drive $($drive.Name) is healthy with $freeSpaceGB GB free." } } |
2. Network Latency Checker (ForEach and For)
Maintaining a healthy network is crucial. This script tests the average latency to each server, identifying potential connectivity issues:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
$servers = @("Server1", "Server2", "Server3") $pingCount = 5 foreach ($server in $servers) { $totalTime = 0 for ($i = 1; $i -le $pingCount; $i++) { $ping = Test-Connection -ComputerName $server -Count 1 -Quiet if ($ping) { $response = Test-Connection -ComputerName $server -Count 1 $totalTime += $response.ResponseTime } } if ($totalTime -gt 0) { $averageTime = [math]::Round($totalTime / $pingCount, 2) Write-Output "Average ping time to $server is $averageTime ms." } else { Write-Output "$server is offline." } } |
3. Bulk User Account Creation (ForEach and If-Else)
Creating multiple user accounts is a common task, especially during employee onboarding. This script automates the process:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$usernames = @("User1", "User2", "User3") $password = ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force foreach ($username in $usernames) { if (!(Get-LocalUser -Name $username -ErrorAction SilentlyContinue)) { New-LocalUser -Name $username -Password $password -FullName "$username Account" -Description "Standard user account" Write-Output "Created user account: $username" } else { Write-Output "User account $username already exists." } } |
4. Log File Cleanup (ForEach, For, and If-Else)
Old log files can quickly consume disk space. This script removes logs older than 30 days from multiple directories:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$directories = @("C:\Logs\App1", "C:\Logs\App2", "C:\Logs\App3") $daysOld = 30 foreach ($directory in $directories) { $files = Get-ChildItem -Path $directory -Filter "*.log" for ($i = 0; $i -lt $files.Count; $i++) { if ($files[$i].LastWriteTime -lt (Get-Date).AddDays(-$daysOld)) { Remove-Item -Path $files[$i].FullName -Force Write-Output "Deleted: $($files[$i].FullName)" } } } |
5. Service Status Checker (ForEach, For, and If-Else)
This script checks the status of a specific service on multiple servers, ensuring critical services are always running:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
$servers = @("Server1", "Server2", "Server3") $serviceName = "W32Time" foreach ($server in $servers) { try { $services = Get-Service -ComputerName $server -Name $serviceName for ($i = 0; $i -lt $services.Count; $i++) { if ($services[$i].Status -eq "Running") { Write-Output "$($services[$i].DisplayName) on $server is running." } else { Write-Output "$($services[$i].DisplayName) on $server is not running." } } } catch { Write-Output "Unable to connect to $server." } } |
6. Directory Size Checker (While)
Monitors the size of a directory, sending alerts if it exceeds a threshold:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$directory = "C:\Logs" $thresholdGB = 5 while ($true) { $sizeGB = (Get-ChildItem -Path $directory -Recurse | Measure-Object Length -Sum).Sum / 1GB if ($sizeGB -gt $thresholdGB) { Write-Output "Warning: Directory $directory is over $thresholdGB GB." break } Start-Sleep -Seconds 60 } |
7. System Uptime Checker (Switch)
This script uses a switch statement to categorize server uptime:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$uptime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime $daysUp = (New-TimeSpan -Start $uptime -End (Get-Date)).Days switch ($daysUp) { {$_ -lt 7} { Write-Output "Server recently rebooted ($daysUp days up)." } {$_ -lt 30} { Write-Output "Server is stable ($daysUp days up)." } default { Write-Output "Server is highly stable ($daysUp days up)." } } |
Conclusion
Mastering these PowerShell loops and conditionals can significantly enhance your Windows system administration skills. From automating routine maintenance to managing complex server environments, these examples demonstrate the power and flexibility of PowerShell. With practice, you’ll find yourself building even more sophisticated scripts that reduce manual effort, improve efficiency, and ensure the smooth operation of your IT infrastructure. Keep experimenting and expanding your PowerShell toolkit to stay ahead in the world of Windows administration.
Become an Azure Expert in Just 2 Months with Industry-Certified Trainers
- Career-Boosting Skills
- Hands-on Labs
- Flexible Learning
About CloudThat
CloudThat is an award-winning company and the first in India to offer cloud training and consulting services worldwide. As a Microsoft Solutions Partner, AWS Advanced Tier Training Partner, and Google Cloud Platform Partner, CloudThat has empowered over 850,000 professionals through 600+ cloud certifications winning global recognition for its training excellence including 20 MCT Trainers in Microsoft’s Global Top 100 and an impressive 12 awards in the last 8 years. CloudThat specializes in Cloud Migration, Data Platforms, DevOps, IoT, and cutting-edge technologies like Gen AI & AI/ML. It has delivered over 500 consulting projects for 250+ organizations in 30+ countries as it continues to empower professionals and enterprises to thrive in the digital-first world.
WRITTEN BY Naveen H
Comments