Monitoring scripts with email alerts in PowerShell - Time & Space Complexity
When running monitoring scripts that send email alerts, it's important to know how the script's work grows as it checks more items.
We want to understand how the time to complete changes when the number of checks increases.
Analyze the time complexity of the following code snippet.
$servers = @('server1', 'server2', 'server3')
foreach ($server in $servers) {
$status = Test-Connection -ComputerName $server -Count 1 -Quiet
if (-not $status) {
Send-MailMessage -To 'admin@example.com' -Subject "Alert: $server down" -Body "Server $server is not responding."
}
}
This script checks each server's status once and sends an email alert if the server is down.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each server to test its connection.
- How many times: Once per server in the list.
As the number of servers increases, the script checks each one individually, so the total work grows directly with the number of servers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 connection checks, up to 10 email sends |
| 100 | 100 connection checks, up to 100 email sends |
| 1000 | 1000 connection checks, up to 1000 email sends |
Pattern observation: The work grows steadily and directly with the number of servers.
Time Complexity: O(n)
This means the time to run the script increases in a straight line as you add more servers to check.
[X] Wrong: "Sending emails inside the loop doesn't affect the time complexity because emails are sent quickly."
[OK] Correct: Sending an email is part of the repeated work and happens once per server that is down, so it adds to the total time as the number of servers grows.
Understanding how monitoring scripts scale helps you write efficient checks and alerts, a useful skill in real-world system management.
"What if we added a nested loop to check multiple services per server? How would the time complexity change?"