You’re looking through a PowerShell script you wrote a few months ago and come across this:

if ($Server.Status -eq 3) {
    Restart-Computer -ComputerName $Server.Name
}

The code is simple enough, but there’s an immediate problem: what does 3 mean?

Maybe it means the server is in maintenance mode. Perhaps it means there was an error or a reboot is required. You probably knew exactly what it meant when you wrote the script, but that meaning isn’t obvious from the code itself.

This is a classic example of a magic number: a numeric value used directly in code without making its purpose clear.

Give the number a name

Suppose 3 means the server is in maintenance mode. A simple improvement is to give the value a descriptive name:

$MaintenanceStatus = 3

if ($Server.Status -eq $MaintenanceStatus) {
    Restart-Computer -ComputerName $Server.Name
}

The behaviour hasn’t changed, but the code is easier to understand. You don’t need to remember what 3 represents because the variable tells you.

This becomes even more useful when an application or API uses several numeric values. Imagine an API returning the following statuses:

0 = Unknown
1 = Online
2 = Offline
3 = Maintenance
4 = Error

You could work with those numbers directly:

switch ($Server.Status) {
    1 { Write-Host 'Server is online.' }
    2 { Write-Host 'Server is offline.' }
    3 { Write-Host 'Server is in maintenance mode.' }
    4 { Write-Warning 'Server reported an error.' }
    default { Write-Warning 'Server an unknown status.' }
}

This works perfectly well, but anyone reading the script needs to know what those numbers represent. You could create variables such as $StatusOnline and $StatusMaintenance, but when several values belong together, an enum is often a better fit.

Using an enum

An enum lets you define all possible values and their meaning in one place:

enum ServerStatus {
    Unknown     = 0
    Online      = 1
    Offline     = 2
    Maintenance = 3
    Error       = 4
}

If the API returns 3, PowerShell can convert it to our enum:

$ServerStatus = [ServerStatus]$Server.Status

$ServerStatus

Instead of 3, we now get:

Maintenance

We can also use the enum throughout the rest of the script:

$ServerStatus = [ServerStatus]$Server.Status

switch ($ServerStatus) {
    Online {
        Write-Host 'Server is online.'
    }

    Offline {
        Write-Host 'Server is offline.'
    }

    Maintenance {
        Write-Host 'Server is in maintenance mode.'
    }

    Error {
        Write-Warning 'Server reported an error.'
    }
}

The API can continue to use integers while our PowerShell code works with names that are much easier to understand.

Read also: Enums in PowerShell: Strongly Typed Values for Robust Scripts

Magic numbers aren’t always status codes

Another common example is a threshold:

if ($FreeSpaceGB -lt 15) {
    Send-Alert
}

The interesting part here isn’t the number itself, but why we chose 15. Apparently, 15 GB is the point at which we want to send an alert. Giving that value a name makes the intention clear:

$MinimumFreeSpaceGB = 15

if ($FreeSpaceGB -lt $MinimumFreeSpaceGB) {
    Send-Alert
}

Retry logic has the same problem. Compare this:

if ($RetryCount -ge 5) {
    throw 'Maximum retry count reached.'
}

with:

$MaximumRetryAttempts = 5

if ($RetryCount -ge $MaximumRetryAttempts) {
    throw 'Maximum retry count reached.'
}

Both do exactly the same thing, but the second version tells you why 5 is there.

Timeouts are another common source of magic numbers, especially because the unit isn’t always obvious:

$Client.Timeout = 30000

What does 30000 represent? Seconds? Milliseconds? Something specific to the client? Even if you can’t change how the underlying API expects the value, you can make its purpose clearer:

$RequestTimeoutMilliseconds = 30000

$Client.Timeout = $RequestTimeoutMilliseconds

Now there’s much less room for confusion.

Maybe it should be configuration instead

There’s another question worth asking when you find a magic number: should the value be in the script at all?

Consider these settings:

$MinimumFreeSpaceGB   = 15
$MaximumRetryAttempts = 5
$RetryIntervalSeconds = 30

Giving them descriptive names is already an improvement, but these values look more like configuration than part of the script’s logic. If the same script is used in different environments, it might make sense to move them into a JSON file:

{
    "MinimumFreeSpaceGB": 15,
    "MaximumRetryAttempts": 5,
    "RetryIntervalSeconds": 30
}

PowerShell can then load the configuration:

$Config = Get-Content -Path '.\config.json' -Raw |
    ConvertFrom-Json

if ($FreeSpaceGB -lt $Config.MinimumFreeSpaceGB) {
    Send-Alert
}

This also means you can change a threshold or retry count without having to modify the script itself.

Not every number needs a name

It’s easy to take this idea too far. The goal isn’t to remove every number from your PowerShell scripts. Some numbers are already clear from the context. Take this calculation:

$PercentageUsed = ($UsedSpace / $TotalSpace) * 100

Turning 100 into something like $PercentageMultiplier wouldn’t improve the code. If anything, it would make a simple calculation harder to read.

A good question to ask is: would someone reading this code understand why this particular number is being used?

For $PercentageUsed, the answer is probably yes. For $Server.Status -eq 3, probably not.

What about comments?

You could also explain the value with a comment:

# Status 3 means maintenance
if ($Server.Status -eq 3) {
    Restart-Computer -ComputerName $Server.Name
}

That’s better than leaving the meaning unexplained, but I would rather put that information directly into the code:

$MaintenanceStatus = 3

if ($Server.Status -eq $MaintenanceStatus) {
    Restart-Computer -ComputerName $Server.Name
}

Comments are more useful for explaining why something is being done. If you need a comment just to explain what 3 means, giving the value a proper name is usually the cleaner option.

Conclusion

Magic numbers won’t stop your PowerShell script from working, but they can make it unnecessarily difficult to understand later. A number that seems obvious while you’re writing a script may be a lot less obvious six months from now.

For individual values, a descriptive variable is often enough. If several related numbers represent a fixed set of states, an enum can be a cleaner solution. And if you’re dealing with values such as thresholds, retry counts or timeouts that may differ between environments, they might belong in configuration instead.

You don’t need to replace every number in your scripts. Just ask yourself whether its meaning is obvious from the surrounding code.

If you come across $Status -eq 3 a year from now, will you immediately know what 3 means? If not, you’ve probably found a magic number.

Leave a Reply

Your email address will not be published. Required fields are marked *