Variables and Data Types

PowerShell variables, strings, numbers, booleans, $null, casting and type constraints, automatic and environment variables, and dates, with the conversion traps that cause real bugs.

By The Dark DebuggerUpdated 21 min read

This article covers how PowerShell stores values: variables, the common data types, how values convert from one type to another, and the built-in automatic and environment variables your scripts will rely on. It assumes you've worked through The Object Pipeline and know Get-Member. The next article, Comparison, Logical, and Arithmetic Operators, builds directly on the type rules explained here.

Why types matter in a "scripting" language

PowerShell converts types for you, quietly, most of the time. That's convenient until it isn't. Picture a disk-space check whose threshold lives in a small config file containing 500, and an alert that should fire when usage goes above it:

Set-Content -Path limit.txt -Value '500'
$limit = Get-Content limit.txt
$limit -gt 1000
[int]$limit -gt 1000
$limit.GetType().Name
True
False
String

"Is 500 greater than 1000?" came back True. Get-Content returns text, and when the left side of a comparison is a string, PowerShell compares as strings: "5" sorts after "1", so "500" is "greater". Cast to [int] and the answer is right. This article is about knowing which type you have, and making it the type you want.

Variables

A variable name starts with $. Assignment needs no declaration, and names are case-insensitive:

$server = 'web01'
$port = 8080
"$server listens on $port"
web01 listens on 8080

$SERVER returns web01 too. Stick to letters, digits and underscores. (Braces allow any name, as in ${log file} = 'payment service.log', but save that for when you have no choice.)

Variables are also items on the variable: drive, so the usual cmdlets work on them: Get-Variable -Name server, port lists both with their values, and Remove-Variable -Name port deletes one, after which Test-Path variable:port returns False. Set-Variable can also create read-only variables for values that must not change mid-script:

Set-Variable -Name maxRetries -Value 3 -Option ReadOnly
$maxRetries = 5
WriteError:
Line |
   2 |  $maxRetries = 5
     |  ~~~~~~~~~~~~~~~
     | Cannot overwrite variable maxRetries because it is read-only or constant.

Catch typos with strict mode

By default, reading a variable that was never set gives $null silently. A typo then becomes an empty value instead of an error:

$serverName = 'web01'
"Connecting to [$serverNmae]"
Connecting to []

Set-StrictMode turns that into an error. I recommend it at the top of every script you care about:

Set-StrictMode -Version Latest
"Connecting to [$serverNmae]"
InvalidOperation:
Line |
   2 |  "Connecting to [$serverNmae]"
     |                  ~~~~~~~~~~~
     | The variable '$serverNmae' cannot be retrieved because it has not been set.

Strings

Single quotes are literal; double quotes expand variables and expressions:

$name = 'web01'
'Host: $name'
"Host: $name"
Host: $name
Host: web01

My rule: single quotes by default, double quotes when you want something expanded. Inside double quotes, the escape character is the backtick: `n is a newline, `t a tab, `$ a literal dollar sign:

"Path:`t/var/log`nDone"
Path:	/var/log
Done

To put a quote of the same kind inside a string, double it: 'It''s up' gives It's up, and "She said ""restart it""" gives She said "restart it".

Subexpressions: $( )

Double quotes expand a variable, not an expression. To insert a property, a method call or any calculation, wrap it in $( ):

$file = Get-Item logs/error.log
"Size: $($file.Length) bytes, last write $($file.LastWriteTime.ToString('HH:mm'))"
"Total: $(2 + 3)"
Size: 36023 bytes, last write 19:47
Total: 5

Forgetting the $( ) around a property is one of the most common PowerShell bugs; it's the first item in Common mistakes.

Here-strings

For multi-line text such as config files, email bodies or SQL, use a here-string. @" ... "@ expands; @' ... '@ is literal:

$port = 8080
$config = @"
server=$name
port=$port
generated=$(Get-Date -Format 'yyyy-MM-dd')
"@
$config
server=web01
port=8080
generated=2026-11-09

The single-quoted form keeps $name and $(2 + 3) exactly as typed, which is what you want for templates and code snippets. The opening @" must end its line, and the closing "@ must start at the very beginning of a line. String formatting with -f, -split, -join and -replace are covered in String Formatting, Split, Join, Replace, and Other Operators.

Numbers

PowerShell picks a numeric type from how you write the literal, and GetType() tells you which:

(42).GetType().Name
(3000000000).GetType().Name
(3.14).GetType().Name
(19.99d).GetType().Name
(42L).GetType().Name
Int32
Int64
Double
Decimal
Int64
TypeAcceleratorUse it for
Int32[int]Counts, ports, indexes. Up to 2,147,483,647.
Int64[long]File sizes, byte counts, anything that can pass 2 GB. Suffix L.
Double[double]Measurements and ratios, where tiny rounding errors are acceptable.
Decimal[decimal]Money and anything that must add up exactly. Suffix d.

PowerShell also understands size suffixes, hex and exponents: 10GB is 10737418240, 0xFF is 255 and 1e3 is 1000. The suffixes are binary (1 KB = 1,024 bytes), which matches how file sizes are reported.

Arithmetic surprises

When an [int] calculation overflows, PowerShell widens the result to Double rather than wrapping around:

[int]::MaxValue
[int]::MaxValue + 1
([int]::MaxValue + 1).GetType().Name
2147483647
2147483648
Double

Division always gives the mathematically correct answer, so integer division can return a Double:

7 / 2
(7 / 2).GetType().Name
6 / 2
(6 / 2).GetType().Name
3.5
Double
3
Int32

Converting back to [int] rounds (it doesn't truncate), and it rounds halves to the nearest even number, known as banker's rounding. [math]::Round does the same unless you ask otherwise:

[int]2.5
[int]3.5
[int](7 / 2)
[math]::Floor(7 / 2)
[math]::Round(2.5)
[math]::Round(2.5, [MidpointRounding]::AwayFromZero)
2
4
4
3
2
3

Use [math]::Floor when you want "how many whole batches fit", and AwayFromZero when a human expects 2.5 to become 3. The remainder operator is %: 7 % 3 is 1.

Finally, Double can't represent most decimal fractions exactly:

0.1 + 0.2
(0.1 + 0.2) -eq 0.3
(0.1d + 0.2d) -eq 0.3d
0.3
False
True

The display rounds to 0.3, but the stored value isn't exactly 0.3. For money, use [decimal].

Booleans and truthiness

The boolean values are $true and $false. In an if or a [bool] cast, every value counts as either true or false:

[bool]'false'
[bool]''
[bool]0
[bool]'0'
[bool]@()
[bool]$null
True
False
False
True
False
False
FalseTrue
$false, 0, 0.0any non-zero number
'' (empty string)any non-empty string, including 'false' and '0'
$nullany object
an empty arrayan array with at least one truthy element

The 'false' row matters when booleans arrive as text from a CSV, an API or an environment variable: [bool]'false' is True. Compare the text instead, for example $value -eq 'true', or parse it with [bool]::Parse($value).

$null

$null means "no value". Reading a property of $null quietly gives nothing, and .Count gives 0, which makes code forgiving:

$missing = $null
$missing.Name
$missing.Count
0

Calling a method on it is an error:

$missing.ToUpper()
InvalidOperation: You cannot call a method on a null-valued expression.

When you see that error, something you expected to have a value (a lookup result, a config setting, a command's output) was empty. Also put $null on the left of comparisons. With an array on the left, -eq filters the array instead of answering yes or no:

$servers = @('web01', $null, 'web03')
($servers -eq $null).Count
$null -eq $servers
1
False

$servers -eq $null returned the one $null element; $null -eq $servers correctly says the array itself isn't null. Operators explains this filtering behaviour in full.

Casting and type constraints

Put a type in square brackets in front of a value to convert it:

[int]'42'
[int]'42abc'
42
InvalidArgument:
Line |
   2 |  [int]'42abc'
     |  ~~~~~~~~~~~~
     | Cannot convert value "42abc" to type "System.Int32". Error: "The input string '42abc' was not in a correct format."

(Windows PowerShell 5.1 words the inner message differently: Input string was not in a correct format.) If you'd rather get $null than an error, use -as:

'42abc' -as [int]
('8080' -as [int]) + 1
8081

The first line printed nothing, because the result was $null. To test a type without converting, use -is: 42 -is [int] is True, '42' -is [int] is False.

Type constraints

A type in front of the variable at assignment time constrains it for its whole life. Every later assignment is converted, or rejected:

[int]$port = 8080
$port = '9090'
$port.GetType().Name
$port = 'http'
Int32
MetadataError:
Line |
   4 |  $port = 'http'
     |  ~~~~~~~~~~~~~~
     | Cannot convert value "http" to type "System.Int32". Error: "The input string 'http' was not in a correct format."

'9090' became the integer 9090; 'http' was refused at the moment of assignment, not three functions later. Constraints work for arrays too: after [int[]]$ports = '80', '443', each element is an Int32. And in reverse, [string]$label = 42 stores the string '42'. Script and function parameters use exactly this mechanism, as the -KeepDays example below shows.

Casting dates: invariant culture

Casting text to [datetime] always uses the invariant culture, which reads ambiguous dates US-style, month first, whatever your computer's regional settings:

[datetime]'2026-11-09'
[datetime]'11/09/2026'
[datetime]'09/11/2026'
 
Monday, 09 November 2026 00:00:00
Monday, 09 November 2026 00:00:00
Friday, 11 September 2026 00:00:00
 

To a reader in the UK or India, 09/11/2026 is 9 November; to the cast it's 11 September. Use ISO 8601 (yyyy-MM-dd) everywhere you control the format, and ParseExact (in the dates section) when you don't.

Finding out what you have: GetType()

When in doubt, ask. (Get-Date).GetType().FullName is System.DateTime, (Get-Item logs/error.log).GetType().FullName is System.IO.FileInfo, @(1, 2).GetType().Name is Object[] and @{ a = 1 }.GetType().Name is Hashtable. Arrays and hashtables get a full treatment in Arrays, Hashtables, and Custom Objects.

Automatic variables

PowerShell maintains a set of variables for you. The ones you'll use most:

VariableHolds
$_ / $PSItemThe current pipeline object (see the pipeline).
$?True if the last command succeeded, False if it failed.
$LASTEXITCODEThe exit code of the last native program (or script that called exit).
$PSScriptRootThe folder containing the running script.
$PSCommandPathThe full path of the running script.
$HOME, $PWD, $PIDYour home folder, the current location, this process's ID.
$PSVersionTableVersion information.
$IsWindows, $IsLinux, $IsMacOSWhich OS you're on. PowerShell 7 only.
$ErrorRecent errors, newest first.
$true, $false, $nullThe constants.

On my Linux lab, $IsLinux; $IsWindows; $IsMacOS printed True, False, False. In Windows PowerShell 5.1 the three $Is... variables don't exist, so $IsWindows is $null there, which is falsy. A script that does if ($IsWindows) { ... } will skip the Windows branch on 5.1, the one place it was guaranteed to be on Windows. Test $PSVersionTable.PSEdition -eq 'Desktop' first if your script must support both.

$? and $LASTEXITCODE

$? tells you whether the last command succeeded, for cmdlets and native programs alike:

ls /nonexistent
$?
/usr/bin/ls: cannot access '/nonexistent': No such file or directory
False

$LASTEXITCODE holds the native program's actual exit code, which carries more information:

bash -c 'exit 3'
$LASTEXITCODE
3

Check $? immediately. Every statement updates it, including the one that reads $LASTEXITCODE: in my test, ls /nonexistent followed by $LASTEXITCODE and then $? printed 2 and then True, because displaying $LASTEXITCODE succeeded.

$PSScriptRoot: paths relative to the script

Scripts usually need files that sit next to them: config, templates, modules. $PWD is wherever the user happens to be; $PSScriptRoot is wherever the script is:

# show-paths.ps1 - where am I, and where is this script?
"Current location : $PWD"
"Script folder    : $PSScriptRoot"
"Script file      : $PSCommandPath"
"Config would be  : $(Join-Path $PSScriptRoot 'settings.json')"

Run it from a different folder and the difference is clear:

Set-Location logs
../show-paths.ps1
Current location : /home/sid/demo/logs
Script folder    : /home/sid/demo
Script file      : /home/sid/demo/show-paths.ps1
Config would be  : /home/sid/demo/settings.json

Always build paths to a script's own files from $PSScriptRoot. Scheduled tasks and CI jobs often start in a different working directory than you expect.

Environment variables

Environment variables live on the env: drive and read like variables with an env: prefix: on my Linux lab, $env:HOME is /home/sid and $env:USER is sid. PATH is one string; split it on the platform's separator (: on Linux and macOS, ; on Windows) rather than hard-coding either:

$env:PATH -split [System.IO.Path]::PathSeparator | Select-Object -First 3
/home/sid/.local/opt/powershell/7.6.9
/home/sid/.local/bin
/usr/local/sbin

Setting one affects the current PowerShell process and every program it starts:

$env:APP_ENV = 'staging'
bash -c 'echo "child process sees APP_ENV=$APP_ENV"'
child process sees APP_ENV=staging

Remove-Item env:APP_ENV removes it again. These changes vanish when the session ends. To set a variable permanently on Windows, use [Environment]::SetEnvironmentVariable('APP_ENV', 'staging', 'User') (not run here, since it changes the host); on Linux, put an export line in your shell's startup file.

For "use the environment variable if it's set, otherwise a default", PowerShell 7 has the ?? operator (not available in 5.1):

$logLevel = $env:LOG_LEVEL ?? 'info'
$logLevel
info

Dates and times

Get-Date returns a DateTime. Format it with .NET format strings, or with Unix-style -UFormat codes if those are what you know:

Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
Get-Date -Format o
Get-Date -UFormat '%Y-%m-%d %H:%M'
(Get-Date).ToString('yyyyMMdd-HHmmss')
2026-11-09 21:54:57
2026-11-09T21:54:57.9991690-05:00
2026-11-09 21:54
20261109-215458

-Format o is the round-trip ISO 8601 format with time zone offset, the best choice for logs and APIs. yyyyMMdd-HHmmss sorts correctly as text, which makes it ideal in file names. Watch the case: MM is month, mm is minutes, HH is 24-hour, hh is 12-hour.

Subtracting dates gives a TimeSpan; adding uses methods:

$deadline = [datetime]'2026-12-31T17:00:00'
$left = $deadline - (Get-Date)
$left.GetType().Name
"{0} days, {1} hours" -f $left.Days, $left.Hours
TimeSpan
51 days, 19 hours

Going the other way, (Get-Date '2026-11-09').AddDays(-30).ToString('yyyy-MM-dd') gives 2026-10-10, the kind of cutoff date a retention script needs. There are AddHours, AddMonths and friends for the other units. For text in a known, non-ISO format, ParseExact removes all guessing:

[datetime]::ParseExact('09/11/2026 14:05', 'dd/MM/yyyy HH:mm', [cultureinfo]::InvariantCulture)
 
Monday, 09 November 2026 14:05:00
 

Log timestamps in ISO format cast directly, which makes them easy to work with:

$line = Get-Content 'logs/worker.log' -TotalCount 1
$line
$when = [datetime]$line.Substring(0, 19)
$when.DayOfWeek
2026-11-09T00:00:01 WARN  [worker] slow query took 2140 ms
Monday

For UTC, PowerShell 7.1 and later have Get-Date -AsUTC (5.1 rejects the parameter), and (Get-Date).ToUniversalTime() works everywhere. Servers in different time zones should log and compare in UTC.

A first look at scope

A variable assigned inside a function is local to that function. It doesn't change a variable with the same name outside:

$count = 0
function Add-Request { $count = $count + 1; "inside: $count" }
Add-Request
"outside: $count"
inside: 1
outside: 0

The function could read the outer $count (0), but assigning created a new local $count. This protects you from functions clobbering each other's variables. Scope modifiers such as $script:count, and why you should usually return values instead of modifying outer variables, are covered in Scripts, Scope, and Modules.

Conversion traps: the left side decides

When the two sides of an operator have different types, PowerShell converts the right side to the type of the left side:

"10" + 5
5 + "10"
"10" * 3
3 * "10"
105
15
101010
30

String plus number concatenates; number plus string adds; string times number repeats the string. Comparisons follow the same rule, which is the bug from the start of this article:

"10" -gt 9
10 -gt "9"
False
True

As text, "10" is less than "9", because "1" comes before "9". If the right side can't be converted, you get an error instead of a guess:

5 + "five"
InvalidArgument: Cannot convert value "five" to type "System.Int32". Error: "The input string 'five' was not in a correct format."

The fix is always the same: cast explicitly when values come from outside (files, CSV, user input, APIs, environment variables), and preferably constrain the variable so it stays typed.

Where you'll use this

Almost every operational script starts the same way: read settings from parameters and the environment with defaults, build names from dates, and compute a cutoff. Here's a complete one for planning a backup and clean-up of the release folder from the pipeline article:

# backup-plan.ps1 - work out a backup name and which old release artifacts fall outside retention
param(
    [string]$Service = 'shop-api',
    [int]$KeepDays = 60,
    [string]$ReleaseDir = (Join-Path $PSScriptRoot 'releases')
)
 
# Settings from the environment, with defaults
$environment = if ($env:APP_ENV) { $env:APP_ENV } else { 'dev' }
[int]$maxArchives = if ($env:MAX_ARCHIVES) { $env:MAX_ARCHIVES } else { 5 }
 
# Names and dates
$now     = Get-Date
$stamp   = $now.ToString('yyyyMMdd-HHmmss')
$archive = "${Service}_${environment}_$stamp.tar.gz"
$cutoff  = $now.Date.AddDays(-$KeepDays)
 
# Old artifacts
$old = Get-ChildItem -Path $ReleaseDir -Filter '*.tar.gz' |
    Where-Object { $_.LastWriteTime -lt $cutoff }
$oldBytes = ($old | Measure-Object -Property Length -Sum).Sum
 
[pscustomobject]@{
    Environment   = $environment
    ArchiveName   = $archive
    Cutoff        = $cutoff.ToString('yyyy-MM-dd')
    OldArtifacts  = $old.Count
    ReclaimableMB = [math]::Round($oldBytes / 1MB, 1)
    MaxArchives   = $maxArchives
    MaxArchivesIs = $maxArchives.GetType().Name
}

Every idea from this article is in there: typed parameters, environment variables with defaults (written with if/else rather than ??, which 5.1 doesn't have), a type-constrained [int]$maxArchives, braces in "${Service}_${environment}_...", a sortable timestamp, and date arithmetic. With nothing set:

./backup-plan.ps1
 
Environment   : dev
ArchiveName   : shop-api_dev_20261109-215458.tar.gz
Cutoff        : 2026-09-10
OldArtifacts  : 5
ReclaimableMB : 202.7
MaxArchives   : 5
MaxArchivesIs : Int32
 

With production settings from the environment, and the retention passed as a string:

$env:APP_ENV = 'prod'; $env:MAX_ARCHIVES = '12'
./backup-plan.ps1 -KeepDays '120'
Remove-Item env:APP_ENV, env:MAX_ARCHIVES
 
Environment   : prod
ArchiveName   : shop-api_prod_20261109-215458.tar.gz
Cutoff        : 2026-07-12
OldArtifacts  : 2
ReclaimableMB : 76.2
MaxArchives   : 12
MaxArchivesIs : Int32
 

'120' and '12' were converted to integers by the constraints, so MaxArchivesIs is still Int32. Nonsense is rejected before the script does anything:

./backup-plan.ps1 -KeepDays 'thirty'
backup-plan.ps1: Cannot process argument transformation on parameter 'KeepDays'. Cannot convert value "thirty" to type "System.Int32". Error: "The input string 'thirty' was not in a correct format."

That early, clear failure is exactly what you want from a script that will eventually delete files.

Common mistakes

Putting a property inside double quotes without $( )

$file = Get-Item logs/error.log
"Size: $file.Length"
Size: /home/sid/demo/logs/error.log.Length

Only $file was expanded (a file object turns into its full path as text), and .Length was treated as literal text. Write "Size: $($file.Length)".

A variable name that swallows the next character

Underscores, letters and digits are valid in variable names, so PowerShell reads $name_backup as one (unset) variable:

"$name_backup.tar.gz"
"${name}_backup.tar.gz"
.tar.gz
web01_backup.tar.gz

Braces mark where the name ends. A dot or a hyphen ends a name by itself, which is why "$name.example.com" correctly gives web01.example.com. Set-StrictMode -Version Latest would have turned the first line into an error instead of an empty string.

Indenting the closing marker of a here-string

Indenting a here-string's closing "@ to line up with the surrounding code is a parse error. I did exactly that inside a function:

function Get-AppConfig {
    $config = @"
server=web01
port=8080
    "@
    $config
}
Get-AppConfig
ParserError: /home/sid/demo/bad-config.ps1:5
Line |
   5 |      "@
     |      ~~
     | White space is not allowed before the string terminator.

The closing marker must start in column 1, even inside indented code. It looks odd in an indented function, but there's no way around it.

Using Windows-style environment variable names on Linux

Windows treats environment variable names case-insensitively; Linux and macOS don't. On Linux:

$env:Path
Test-Path env:Path
Test-Path env:PATH
False
True

$env:Path printed nothing at all. A script written on Windows that reads $env:Path gets an empty string on Linux and, for example, fails to find any tools. Use the exact case the OS uses: PATH, HOME, USER on Unix systems.

Summary

  • Variables start with $, need no declaration, and are case-insensitive. Use Set-StrictMode -Version Latest so typos in variable names become errors.
  • Single quotes are literal, double quotes expand; use $( ) for anything beyond a plain variable and ${name} when the next character could continue the name.
  • Integers overflow to Double, / can return a Double, and [int] rounds halves to even. Use [long] for sizes and [decimal] for money.
  • 'false', '0' and any non-empty string are truthy; empty strings, 0, $null and empty arrays are falsy.
  • Call methods only on values that can't be $null, and put $null on the left of comparisons.
  • Casts ([int]'42') convert once; constraints ([int]$port) convert or reject every future assignment. -as returns $null instead of throwing.
  • The left operand's type decides conversions: "10" + 5 is "105", "10" -gt 9 is False. Cast values that come from files, CSV, APIs and environment variables.
  • [datetime] casts read ambiguous dates month-first; prefer ISO 8601 and ParseExact.
  • $? reflects the very last statement, $LASTEXITCODE the last native exit code, and $PSScriptRoot the script's own folder.

Exercises

Exercise 1: A log file nameeasy

With $host_name = 'web01' and the date 9 November 2026, build the two file names web01-2026-11-09.log and web01_2026-11-09.log. Explain why the second one needs special care.

Show Solution
$host_name = 'web01'
$date = Get-Date '2026-11-09'
"$host_name-$($date.ToString('yyyy-MM-dd')).log"
"${host_name}_$($date.ToString('yyyy-MM-dd')).log"
web01-2026-11-09.log
web01_2026-11-09.log

A hyphen ends a variable name, but an underscore doesn't, so "$host_name_..." would look for a variable called $host_name_. The braces in ${host_name} mark the end of the name. (Don't name the variable $host: $Host is an automatic variable describing the PowerShell host, and $host = 'web01' fails with Cannot overwrite variable Host because it is read-only or constant.)

Exercise 2: Days until a certificate expiresmedium

A TLS certificate's expiry comes back from an API as the string '2027-02-14T00:00:00'. Print the number of whole days left until it expires.

Show Solution
$expires = [datetime]'2027-02-14T00:00:00'
($expires - (Get-Date)).Days
96

I ran this late on 9 November 2026. The cast is safe because the string is ISO 8601, which has no day/month ambiguity. A monitoring script would compare this number against a threshold, such as warning below 30 days, and since it's an [int], that comparison is numeric.

Exercise 3: A validated setting with a defaulthard

Read the maximum upload size in MB from $env:MAX_UPLOAD_MB. If it's missing or not a valid integer, use 25. The result must always be an Int32. Test it with '40' and with 'lots'.

Hint

-as [int] returns $null for text that isn't a number, without throwing an error. But check what it does when the variable doesn't exist at all: run $env:MAX_UPLOAD_MB -as [int] with the variable unset.

Show Solution

The hint's check is the trap: an unset environment variable is $null, and $null -as [int] is 0, not $null:

$env:MAX_UPLOAD_MB -as [int]
0

So "convert, then default if $null" would silently give a limit of 0 MB when the variable is missing. Check for presence first, then for a valid number:

# upload-limit.ps1 - read MAX_UPLOAD_MB, falling back to 25 if it's missing or not a number
$maxUpload = 25
if ($env:MAX_UPLOAD_MB) {
    $parsed = $env:MAX_UPLOAD_MB -as [int]
    if ($null -ne $parsed) { $maxUpload = $parsed }
}
"MAX_UPLOAD_MB='$env:MAX_UPLOAD_MB' -> $maxUpload ($($maxUpload.GetType().Name))"
./upload-limit.ps1
$env:MAX_UPLOAD_MB = '40'; ./upload-limit.ps1
$env:MAX_UPLOAD_MB = 'lots'; ./upload-limit.ps1
Remove-Item env:MAX_UPLOAD_MB
MAX_UPLOAD_MB='' -> 25 (Int32)
MAX_UPLOAD_MB='40' -> 40 (Int32)
MAX_UPLOAD_MB='lots' -> 25 (Int32)

Missing, valid and invalid all behave correctly, and the result is always an Int32. Testing $null -ne $parsed rather than just if ($parsed) also means an explicit 0 is respected instead of being replaced by the default. The if statement itself is covered in Conditionals.


Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2), and Windows PowerShell 5.1.26100.9711 on Windows 11, November 2026. Every PowerShell 7 example ran as shown, in a 100-column terminal against the same demo folder as the pipeline article. Multi-line examples were run as one block, which is why some errors show a Line | marker. The 5.1 notes (the different [int] error wording, $IsWindows being $null, no ?? operator, no Get-Date -AsUTC) come from read-only commands in Windows PowerShell 5.1. The [Environment]::SetEnvironmentVariable call was not run because it would change the host. The surprise: [int]::MaxValue + 1 widens to Double, not Int64. Paths from the test machine's scratch directories are shown shortened to /home/sid/….

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.