Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 34 ยท Language Basics

Variables and Types

Learn PowerShell variables: $name syntax, strong typing with [int] and [string], type accelerators, casting rules, automatic variables, scopes and $null.

A variable is a named box for a value. In PowerShell you make one the moment you assign to it, and every name starts with a dollar sign: $name = 'Ada'. There is no var, no let, and nothing to declare first. Behind that easy surface sits a real type system, because every value is a .NET object (see Objects, Properties and Methods), and PowerShell converts between types automatically in ways that are friendly most of the time and surprising some of the time.

This lesson covers creating and inspecting variables, the strongly typed form [int]$n, the common type accelerators, how casting behaves, the automatic variables PowerShell provides, how scope works, and the special value $null.

Real PowerShell cannot run on this page, so its code is read-only. The runnable examples use a JavaScript stand-in: a small model of typed variables and PowerShell-style casts. It follows the documented rules for the cases shown, but real PowerShell has many more conversions, so treat it as a teaching model.

Variables in PowerShell

Dollar sign Every variable name starts with $.
No declaration Assign and it exists.
Always typed Each value is a .NET object.
Case-insensitive $Name and $name are the same variable.
1 / 2

Creating and using variables

Assign with =, read by writing the name. Names are case-insensitive and can contain letters, digits and underscores:

POWERSHELL
$city = 'Lisbon'
$count = 3
$city          # Lisbon
$CITY          # Lisbon: same variable

A variable holds any object, including collections and results of commands:

POWERSHELL
$files = Get-ChildItem C:\Logs
$files.Count
$files[0].Name

If a name contains spaces or special characters, wrap it in braces: ${my var} = 1. The braces also separate a name from text that follows it in a string (more in Strings, Quoting and Here-Strings). Environment variables live in a separate drive: $env:PATH, $env:USERNAME.

To see what you have, Get-Variable lists variables and Remove-Variable city deletes one. Reading a variable that was never set gives $null, unless strict mode (Set-StrictMode -Version Latest) is on, in which case it is an error. Strict mode is a good habit in scripts because it catches typos like $cuont.

Assigning more than one variable at once is fine too:

POWERSHELL
$a, $b = 1, 2          # $a is 1, $b is 2
$x = $y = 0            # both zero
$first, $rest = 1, 2, 3  # $first is 1, $rest is 2, 3

Types and type accelerators

Ask any value for its type with .GetType():

POWERSHELL
(42).GetType().Name        # Int32
'hi'.GetType().Name        # String
(3.5).GetType().Name       # Double
(Get-Date).GetType().Name  # DateTime

You rarely write full .NET names like System.Int32. PowerShell has short type accelerators in square brackets:

Accelerator Meaning
[int], [long] 32-bit and 64-bit integers
[double], [decimal] Floating point and exact decimal
[string], [char] Text and a single character
[bool] $true or $false
[datetime], [timespan] Dates and durations
[array], [hashtable] Collections (see Arrays and Hashtables)
[pscustomobject] A simple object made of properties
[regex], [guid], [version] Handy .NET classes

Numbers without a decimal point become Int32, and PowerShell widens to Int64 or Double automatically when the value is too big. Literals can carry suffixes and multipliers: 10KB, 5MB, 2GB, 1L for long, 1.5d for decimal, 0xFF for hex.

Strong typing: locking a variable's type

Without a type, a variable can change type on every assignment. Put a type accelerator in front of the variable and the type is locked in:

POWERSHELL
$n = 5
$n = 'five'        # fine, now it is a string

[int]$age = 30
$age = '42'        # converted to the integer 42
$age = 'old'       # error: cannot convert 'old' to System.Int32

Constraining a variable is useful for function parameters (see Functions and Parameters) and for catching mistakes early in a script. The error is raised at the moment of the bad assignment, not later when the value is used.

Casting rules worth knowing

A cast writes the type in front of a value: [int]'42' is 42. PowerShell's conversion rules are generous, with a handful of traps:

  • Strings to numbers: [int]'42' is 42; [int]'abc' is an error. Leading and trailing spaces are tolerated.
  • Fractions to integers round to nearest, and ties go to the even number: [int]2.5 is 2 and [int]3.5 is 4. This is "banker's rounding", not truncation. Use [math]::Floor() or [math]::Truncate() when you need something else.
  • Anything to bool: the number 0, the empty string, $null and an empty array are $false. Any non-empty string is $true, including 'false' and '0'.
  • $null to string and number: [string]$null is an empty string and [int]$null is 0.
  • Strings to dates: [datetime]'2026-03-01' parses the text, using the invariant culture for casts, which is why ISO dates are safest.
  • Comparisons convert to the type of the left operand, a rule that gets its own spot in Operators and Comparison.

You can also use the operators -as and -is: '42' -as [int] returns 42, but returns $null instead of an error when the conversion fails, and 42 -is [int] is $true. They are the right tools when failure is expected.

Automatic variables

PowerShell maintains some variables for you. Do not assign to them (a few are read-only):

Variable Holds
$_ and $PSItem The current object in a pipeline script block
$? Whether the last command succeeded ($true or $false)
$LASTEXITCODE Exit code of the last native program (like ping)
$args Unnamed arguments passed to a script or function
$true, $false, $null The constants
$PSVersionTable Version and edition information
$HOME, $PWD, $PID Home folder, current folder, process id
$PSScriptRoot Folder of the running script
$Error Collection of recent errors, newest first
$MyInvocation Information about how the current command was called

$PSVersionTable.PSVersion tells you whether you are on Windows PowerShell 5.1 or PowerShell 7, which matters for features like ?? and ForEach-Object -Parallel.

Scope

Variables live in scopes. A script, a function and a script block each get their own scope. Reading a variable looks up through parent scopes, but assigning creates a new local variable instead of changing the outer one:

POWERSHELL
$counter = 0
function Add-One { $counter = $counter + 1; $counter }   # local copy!
Add-One         # 1
$counter        # still 0

To deliberately change the outer variable, qualify the name with a scope: $script:counter, $global:counter, or $local:counter. Use $script: for state shared inside one script file, and avoid $global: where you can, because it leaks into the whole session. In ForEach-Object -Parallel and remote script blocks, the $using: prefix brings in the caller's values.

$null: nothing, with care

$null is PowerShell's "no value". It is a constant you cannot assign to. A few behaviours matter:

  • if ($x) is false for $null, but also for 0, empty strings and empty arrays, so test for null explicitly when 0 or '' is a valid value: if ($null -ne $x).
  • Put $null on the left of a comparison: $null -eq $list. If $list is an array, an array on the left filters instead of comparing, as the operators lesson shows.
  • A command that outputs nothing leaves $null in the variable, while a command that outputs one object gives you that object, not a one-item array. Wrap in @() when you need an array either way.
  • Calling a method on $null fails with an error, and strict mode makes undefined variables errors too.

Stand-in: typed variables and casts in JavaScript

The first example models a variable whose type is locked, with a cast function that follows the rules above for int, string, bool and double. Real PowerShell's [int] accepts more (hex strings, for instance), so this covers only the documented basics.

JS Casting like PowerShell

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice [bool] "false" is true because the string is not empty, and that 2.5 and 3.5 round to the even numbers 2 and 4, the same results PowerShell gives.

The second example models [int]$age: a variable that remembers its type and converts every assignment. It also shows the difference between -as (returns null on failure) and a cast (throws).

JS A variable with a locked type

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real: the behaviour you see (the type sticks, the bad assignment fails and leaves the old value, -as gives null). What is the stand-in: the JavaScript mechanism. PowerShell stores the constraint as an attribute on the variable itself.

Add Set-StrictMode -Version Latest near the top of scripts. It turns reads of undefined variables and several other sloppy patterns into errors, which finds typos at once.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After [int]$age = 30, what does $age = 'old' do?

    A type placed before the variable constrains it. Each assignment is converted to that type, and a value that cannot be converted raises an error.
  2. 2. What does [bool]'false' return?

    Any non-empty string converts to $true, including the text 'false'. Only the empty string, 0, $null and an empty array are false.
  3. 3. Inside a function, $counter = $counter + 1 runs while $counter is 0 in the script. What happens to the script's $counter?

    Reading looks through parent scopes, but assigning creates a local variable. Use $script:counter to change the outer one.
  4. 4. What is [int]2.5 in PowerShell?

    Casts round to the nearest integer and send ties to the even number, so 2.5 becomes 2 and 3.5 becomes 4.

Summary

  • Variables start with $, need no declaration, and are case-insensitive; use ${...} for odd names and $env:NAME for environment variables.
  • Every value is a .NET object, so use .GetType() and type accelerators such as [int], [string], [bool] and [datetime].
  • A type in front of a variable ([int]$n) locks its type and converts every assignment, raising an error when it cannot.
  • Casts round to the nearest even integer, treat non-empty strings as true (even 'false'), and -as returns $null instead of failing.
  • Automatic variables such as $_, $?, $args, $PSVersionTable and $PSScriptRoot are provided by PowerShell.
  • Assignments in a function or script block create local variables; use $script: or $global: deliberately.
  • Test $null with $null -eq $x on the left and remember that 0, empty strings and empty arrays are also false.

Continue with Strings, Quoting and Here-Strings.